Change Variable Of Another Script Unity Code Example


Example 1: unity variable from another script


//Make Health public
public class PlayerScript: MonoBehaviour {
public float Health = 100.0f;
}

//Access it.

public class Accessor : MonoBehaviour {
void Start()
{
GameObject thePlayer = GameObject.Find("ThePlayer");
PlayerScript playerScript = thePlayer.GetComponent<PlayerScript>();
playerScript.Health -= 10.0f;
}
}

Example 2: unity how to use variable from another script


using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Miner : MonoBehaviour // A class made to mine coins
{
private Variables variables; // "Variables" is the class name with my variables in it, "variables" is the name of it's variable in this class

void Start()
{
variables = GameObject.Find("ScriptHolder").GetComponent<Variables>(); // "ScriptHolder" is the name of the GameObject that holds the Variables class
}

public void Mine()
{
variables.coins += variables.minePower; // This is how you reference your variables
}
}

Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android How Can I Convert A String To A Editable