I’m having difficulty properly running methods or accessing public variables of scripts attached to cloned gameobjects. For example, the code below will create three GridPiece objects, and successfully move the third object back by 1 unit. However, the 2nd GridPiece does not see any change to its Passable variable.
My GridPieceScript class:
using UnityEngine;
using System.Collections;
public class GridPieceScript : MonoBehaviour {
public bool Passable;
void Start ()
{
Passable = false;
}
void Update ()
{
}
public void MakePassable()
{
Passable = true;
}
}
And my GridControlScript class:
using UnityEngine;
using System.Collections;
public class GridControlScript : MonoBehaviour {
public GameObject GridPiece;
void Start ()
{
GameObject First = (GameObject)Instantiate (GridPiece, new Vector3(0, 0, 0), Quaternion.identity);
GameObject Second = (GameObject)Instantiate (GridPiece, new Vector3(1, 0, 0), Quaternion.identity);
GameObject Third = (GameObject)Instantiate (GridPiece, new Vector3(2, 0, 0), Quaternion.identity);
Second.GetComponent<GridPieceScript>().Passable = true;
Second.GetComponent<GridPieceScript>().MakePassable();
Third.GetComponent<Transform>().Translate(new Vector3(0f, 0f, 1f));
}
void Update ()
{
}
}
Hello,
If we take a look at the order of events that happen:
Frame 1: (The first frame)
-
GridControlScript.Start() is called
- 3 objects are instantiated
-
Awake() is called on the 3 objects
-
Passable is set to true on first and second object
-
Update() is called on GridControlScript
As you can see, Start is not called on the 3 objects yet.
Frame 2: (The second frame)
-
Start() is called on 3 objects, setting Passable to false
-
Update() is called on all objects (in no specific order)
Looking at that, it is obvious why Passable is never set to true. Because Start which sets it to false, is called in the frame after the object has been instantiated.
If you want something to happen after Instantiate, but before anything else, you need to use Awake and not Start.
However, if you want default values for variables, you can simply go:
public bool Passable = false;
However public variables are serialized with Prefabs, so doing this only defaults it for a new script, not a prefab.
To avoid this you can set the variable to be NonSerialized like so:
[NonSerialized]
public bool Passable = false;
As @DaveA said, you should Debug your script. Put Debug.Log calls in important places and see when they happen. You could have answered this yourself by doing exactly that 
Hope this helps,
Benproductions1