Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.

Resolved Can anyone help me with this?

Discussion in 'Scripting' started by Noodle_Meanie, Nov 28, 2022.

  1. Noodle_Meanie

    Noodle_Meanie

    Joined:
    Sep 11, 2021
    Posts:
    45
    So, I'm trying to do a void whenever something collides with a trigger in one script. In the other it uses that void to Debug.Log("Ooga Booga");. The game is fine until I actually collide with the object using the first script, and then unity gives this error.

    NullReferenceException: Object reference not set to an instance of an object
    weaponGrab.OnTriggerEnter2D (UnityEngine.Collider2D Other) (at Assets/weaponGrab.cs:34)

    Here is the code for the first script (C#).

    void OnTriggerEnter2D(Collider2D Other)
    {
    animatorWG.SetInteger("WeaponNumber", 0);
    if (weaponNumber == 1)
    {
    GetComponent<PlayerAttack>().NewWeaponCheck(weaponNumber); <-- line 34
    }
    }

    Here is the code for the second script (C#)

    public void NewWeaponCheck(int weaponNumber)
    {

    Debug.Log("Ooga booga");
    }

    Someone please help and tell me what the problem is. Thank you.
     
    Last edited: Nov 29, 2022
  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    8,885
    Line 34 doesn't have a reference to any object. It's therefore NULL. Of course, we don't know what line 34 is because you didn't use code-tags or say which it was but you can find that line yourself.

    If what you're actually saying is that you don't know what a reference is then you can find lots of C# docs about reference types vs value types online. It's not a Unity thing.
     
  3. Noodle_Meanie

    Noodle_Meanie

    Joined:
    Sep 11, 2021
    Posts:
    45

    Sorry, this is line 34
    GetComponent<PlayerAttack>().NewWeaponCheck(weaponNumber);

    Can you explain how to reference an object?
     
  4. AnimalMan

    AnimalMan

    Joined:
    Apr 1, 2018
    Posts:
    1,164
    Use coding tags young man.
     
  5. Noodle_Meanie

    Noodle_Meanie

    Joined:
    Sep 11, 2021
    Posts:
    45
    Yeah, I know. Next time.
     
  6. Noodle_Meanie

    Noodle_Meanie

    Joined:
    Sep 11, 2021
    Posts:
    45
    I ended up fixing this by trial and error. What I did was just make a Public GameObject called player, and added that to the beginning of line 34,
    player.GetComponent<PlayerAttack>().NewWeaponCheck(weaponNumber);
    After assigning player to my player in the unity editor, it magically worked. This probably isn't the best solution though, and might bite me in the future, but as of right now, it worked.