GetComponent remains null

Hi I am having problems getting my script component out of my game object.
I have assigned GameObjects “Defender” to my buttons. Made public static GameObject “currentDefender” to have easy access to it form another script.

using UnityEngine;
using System.Collections;

public class Button : MonoBehaviour {
    SpriteRenderer fadeAlpha;
    Color currentColor = Color.white;
    Button[] buttonArray;
    public GameObject Defender;
    public static GameObject currentDefender;

    // Use this for initialization
    void Start () {
        buttonArray = GameObject.FindObjectsOfType<Button>();
        currentDefender = Defender;
   
    }

Here i am trying to access Deffender script attached to Defender Object above:

public class DefenderSpawner : MonoBehaviour {
    public Camera myCamera;
    GameObject parent;
    Deffender defenderScript;

    void Start()
    {
        parent = GameObject.Find ("Defenders");

        if (!parent)
        {
            parent = new GameObject("Defenders");
        }
    }



    void OnMouseDown ()
    {
        Vector2 rawPos = CalculateWorldPointOfMouseClick();
        Vector2 roundedPos = SnapToGrid (rawPos);
        GameObject defender = Button.currentDefender;
        defenderScript = defender.GetComponent<Deffender>();

        GameObject newDef = Instantiate(defender, roundedPos, Quaternion.identity) as GameObject;

        newDef.transform.parent = parent.transform;
        Debug.Log(defenderScript);
    }

And my defenderScript keeps returning null. Can anyone please explain to me what is going on .Thank you.

Is “Deffender” supposed to have two Fs in it? (second script lines 4 and 23)

In your first script, you are setting Button.currentDefender equal to “Defender”, but you aren’t initializing Defender. I imagine Defender is probably set in the inspector. However:

  1. Remember that Start() is going to run once for every Button in your scene (including any new one you instantiate at run-time), and they’re all going to try to assign the same variable. If you have one single Button anywhere in your scene, at any time, that has the wrong value for Defender, then it might overwrite the value of currentDefender with the wrong value. (This is probably not the best way to initialize a static variable, for exactly that reason.)

  2. Are you 100% sure that the value you set for Defender actually has a Deffender component? Maybe you should declare Defender to be of type Deffender to make sure that it can only be assigned a Deffender component (you can always get from there back to the actual GameObject with Defender.gameObject).

Thank you Antistone. I actually was addressing parent object (child needed) all this time (hooray late night coding :smile:) .