I want to start by saying I have read this page 10 times, so please don’t just link it.
http://docs.unity3d.com/412/Documentation/ScriptReference/index.Accessing_Other_Game_Objects.html
I have two scripts, playerStats, and gameManagment.
Within gameManagment script I first initialize the other script with awake and then attempt to initialize some standard “players”, attach the playerStats script to them.
I now want to edit each players stat individually, but am having trouble doing so.
The gameManagment script is assigned to an empty gameobject within unity.
I wish to give each new “player” object the playerStats script within gameManagment.
GameManagment script:
public PlayerStats playerStats;
void Awake()
{
playerStats = GetComponent<PlayerStats>();
}
void Start()
{
//create players
GameObject player1 = GameObject.CreatePrimitive(PrimitiveType.Capsule);
player1.transform.position = new Vector3(4,1,0);
player1.AddComponent<PlayerStats>();
player1.tag = "Player";
//player1.PlayerStats.setSpeed(10);
//this line is my intended implementation, but will not compile
GameObject player2 = GameObject.CreatePrimitive(PrimitiveType.Capsule);
player2.transform.position = new Vector3(0,1,4);
player2.AddComponent<PlayerStats>();
player2.tag = "Player";
//playerStats.setSpeed(5);
//this line compiles, but gives me a null reference exception
//at runtime
}
PlayerStats script :
public class PlayerStats : MonoBehaviour {
public float speed = 0;
public float health = 100;
public bool dead = false;
void Start(){
speed = 0;
health = 100;
}
public void setSpeed(float amount)
{
speed = amount;
}