Object reference not set to an instance of an object (Please help)

Hello,

I got a script were iam working on, and testing new things. But i tried to get acces to an script thats is in a gameobject so that i can change variables. The strange thing about this is, that i can change the variable’s but also get a error. Normaly when a line contains errors it’s not working, but in this case it’s stil working :eyes:. I hope someone can see what’s wrong with my code.

using UnityEngine;
using System.Collections;

public class Soldier1_Swing_Sword_Test : MonoBehaviour {

    public RaycastHit hit;
    public int damage;
    public bool hite;
    public float Old_Y;
    public static bool Taken_Damage;
    public static bool good;
    public GameObject soldier1;
    public Soldier1_AI_Test other;
    public bool test;
    // Use this for initialization
    void Start () {
        Taken_Damage = false;
        damage = 20;
        Old_Y = 0.0f;

        other = (Soldier1_AI_Test) soldier1.GetComponent(typeof(Soldier1_AI_Test));
    }
   
    // Update is called once per frame
    void Update () {

//this line gives a error     
test = other.Is_Swinging;
        if(test == true && hite == false){
            if(Physics.Raycast(transform.position, transform.TransformDirection(Vector3.up), out hit)){
                float distance = hit.distance;
                if(hit.transform.tag == "Enemy"){
                    Debug.Log ("Enemy has been hit");
                    hite = true;
                    good = true;
                    hit.transform.SendMessage("ApplyDamage", damage, SendMessageOptions.DontRequireReceiver);
                }

                Old_Y = hit.transform.position.y;
                StartCoroutine(Damage_Timer());
            }
           
        }
        if(good == true){

        }
    }
   
    IEnumerator Damage_Timer(){
        yield return new WaitForSeconds(2.0f);

    }

}

try changing line 21 to:

other = soldier1.GetComponent<Soldier1_AI_Test>();

and just double check that soldier1 contains a Soldier1_AI_Test component.

1 Like
if(test == true && hite ==false){

to

if(other && other.Is_Swinging && !hite){

But yes, it seems like there’s no component of that type attached to that soldier1 GameObject, so it’s returning null and you’re not null-checking it.

Wel, the soldier contains a soldier1 ai, and i the game the code is doing what its suposed to do, but with errors

iam such a fool…

I cloned the soldier to test the combat and only deleted the soldier ai in that clone and forgot to delete the soldier swing test script… the reason why i deleted the AI in the cloned soldier was because i changed the tag to Enemy so that the cloned soldier would be attacked and didn’t attack himself… sorry for opening this thread because of such a dumb mistake hahah.

1 Like