0

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

1 Answer 1

1

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>().

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.