Reputation: 3
I am creating a player controlled object which has a script in its prefab that will highlight the tiles that are valid moves. Script works fine if triggered manually but fails to do so in code
public GameObject player_prefab;
Start(){
GameObject playerUnit = GameObject.Instantiate(player_prefab,PlayerPoss,player_prefab.transform.rotation);
squadEvents squadScript = (squadEvents)playerUnit.GetComponent(typeof(squadEvents));
squadScript.ShowWalkRange();}
Digging around on the internet tells me my problem is the fact I am trying to access the script during start , but I can't find a reason why or come up with a work around, Thanks for any help with these issues
Upvotes: 0
Views: 64
Reputation: 4049
One thing to note is that the Start() method of an instatiated object isn't called until just before its first Update() method call. If you're performing any initialisation in the other object's Start() method, you can move that to the Awake() method.
It might also be that you're not actually finding the component correctly? If you use GetComponentInChildren you'll search for the component on this object or any of the prefabs child objects.
private void Start()
{
GameObject playerUnit = GameObject.Instantiate(player_prefab,PlayerPoss,player_prefab.transform.rotation);
squadEvents squadScript = playerUnit.GetComponentInChildren<squadEvents>();
if ( squadScript == null )
{
Debug.Log("Could not get <squadEvents> component in this GameObject or any of its children.");
return;
}
squadScript.ShowWalkRange();
}
Here's the Unity reference for GetComponentInChildren<T>().
Upvotes: 1