(JS) function call doesn't work in Start() but works in OnGUI()?

Hello,

I’m confused. :stuck_out_tongue: I have a script that instantiates a prefab, then sets some variables on the clone. I wrote a little function to set up these variables, but it does not work in Start() or Awake(). It doesn’t give an error or anything, it just does nothing. However, if I put it in one of the functions I wrote to make a GUI label, it works fine. What am I doing wrong? Is it working but not displaying the changes perhaps?

//my code, minus some unnecessary stuff to save space
var pc : GameObject;
var pcClone : GameObject;
var pcScript : PlayerStats;
var startPoints : int = 100;
var minStartVal : int = 40;
var pointsLeft : int;

function Start()
{
pcClone = Instantiate (pc, Vector3.zero, Quaternion.identity);
pcClone.name = "Hero"; //this works just fine
pcScript = pcClone.GetComponent(PlayerStats);
pointsLeft = startPoints;
//SetupStats(); not sure why this does not work here
}

function SetupStats()
{
pcScript.strength.baseValue = 40;
pcScript.perception.SetBaseValue(minStartVal);
pcScript.intellect.SetBaseValue(minStartVal);
pcScript.endurance.SetBaseValue(minStartVal);
pcScript.coordination.SetBaseValue(minStartVal);
}

function DisplayName()
{
GUI.Label(new Rect(10, 10, 50, 25), "Name");
pcScript.playerName = GUI.TextField(new Rect(65, 10, 100, 25), pcScript.playerName);
SetupStats(); //works ok here, not sure why yet
}

Thanks!
Matt

Does pcScript set it’s values in Start()?

If so that means that PlayerStats.Start() will run after the function you instantiate it in has been called, resetting the previously set values.

Thanks! So, if I move the calls in PlayerStats to Awake() would that take care of the problem, or is there a better way?

Thanks again :slight_smile:
Matt