Accessing Instantiated prefab's script

I have the below codes on 2 objects, one is a prefab just been instantiated and I can’t seem to find why its not working. Could you guys please take a look for me? I had to cut it up to so many lines to check everything, and the myNewBaseScript is always null
cheers
Tom

GameObject myNewBase;

myNewBase = Instantiate(myPrefab, hit.point, Quaternion.LookRotation(2 * (this.transform.position - targetPoint)), this.transform);

if(myNewBase != null) {

   SelectBase myNewBaseScript;
   myNewBaseScript = (SelectBase) myNewBase.GetComponent("SelectBase");
   myBases.Add(myNewBaseScript);

   if(myNewBaseScript != null)
      myNewBaseScript.myBaseId = myBases.Count;

   Debug.Log(myNewBaseScript.myBaseName);
}
public class SelectBase : MonoBehaviour
{
    int BaseId = 0;
    string BaseName = "New Base";

    public GameObject myRenderer;

    [HideInInspector] public string myBaseName {
        get { return BaseName; }
        set { BaseName = value; }
    }

    [HideInInspector] public int myBaseId {
        get { return BaseId; }
        set { BaseId = value; }
    }

I think line 9 should be:

myNewBaseScript =  myNewBase.GetComponent<SelectBase>();

Thanks, but sadly that’s the exact same thing… and throws the exact same nullref exception :frowning:

If you’re getting an exception, always post the exact error message and indicate which line it occurs on.

When you said “myNewBaseScript is always null” I assumed you meant that your code was skipping the “if” block, which would not result in an exception. Sounds like something else is going on.

But if the problem really is that myNewBase.GetComponent is returning null, then that’s probably an issue with your prefab, not your code.

1 Like

yes, it skips the if but if i run it without the if, the line where I use the myBaseId throws the exception.

found the error right now and I was just stupid, sry about it. the script was attached to the child gameobject instead of the baseobject of the prefab so I have to look for it with GetComponentInChildren. Now Im banging my head against the wall wasting half a day for this :frowning: I debugged everything except the name of the myNewBase, that would help me to realise this quicker…

thanks for looking in and still trying to help, appreciate it. it runs now perfectly… :eyes: