#use of gameObject in MonoBehaviour script leads to NullReferenceException

1 messages · Page 1 of 1 (latest)

ashen delta
#

Hi there, I am new to unity and C#, but I am not new to programming.

I got this error when trying to pass gameObject to a method call like like this:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AbilityHandler : MonoBehaviour
{
    public Ability ability;
    // Update is called once per frame
    void Update()
    {

          if (Input.GetKeyDown(key))
                {
                    ability.Activate(gameObject); //<-- error points to this
                }
    }
}

The method that I am calling is from this:

public class Ability : ScriptableObject
{
    public new string name;
    public float cooldownTime;
    public float activeTime;

    public virtual void Activate(GameObject parent){}
}

And I am getting this error:

I was under the impression that gameObject can be referenced anywhere in a MonoBehaviour script

halcyon monolith
#

gameObject is not causing the exception.

#

ability is probably null.

#

gameObject could cause an exception if you tried to access it from a destroyed component

#

but since you're in Update, that seems very unlikely

#

(unity isn't going to call Update on a destroyed component)

ashen delta
#

ability shouldnt be null, I am passing in this right here:

#

Ok I think I figured it out

#

I think it has something to do with the activate method in Teleport

#

This is what I had:

    public override void Activate(GameObject parent)
    {
        // teleport towards the mouse cursor position by teleportDistance

        // get the mouse position in world coordinates
        Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        // get the direction from the player to the mouse
        Vector3 direction = mousePosition - parent.transform.position;
        // normalize the direction vector
        direction.Normalize();
        // multiply the direction vector by the teleportDistance
        direction *= teleportDistance;
        // add the direction vector to the player's position
        Vector3 newPosition = parent.transform.position + direction;
        // set the player's position to the new position
        parent.transform.position = newPosition;
    }

But when I comment it out, it no longer gives me an error

halcyon monolith
#

Oh, right, Teleport.Activate would be the ability's Activate method

halcyon monolith
#

so, which is line 14?

ashen delta
halcyon monolith
#

Do not remove anything from your code.

#

That just makes it harder to understand what's happening.

#

Please share the entire script. I need a clear picture of what's happening here.

#

!code

opaque sapphireBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

ashen delta
#

Sure my bad

// AbilityHandler.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AbilityHandler : MonoBehaviour
{
    public Ability ability;
    float cooldownTime;
    float activeTime;

    enum AbilityState
    {
        Ready,
        Active,
        Cooldown,
    }

    private AbilityState state;

    public KeyCode key;


    // Update is called once per frame
    void Update()
    {
        switch (state) {
            case AbilityState.Ready:
                if (Input.GetKeyDown(key))
                {
                    ability.Activate(gameObject);
                }
                break;
            case AbilityState.Active:
                if (activeTime > 0)
                {
                    activeTime -= Time.deltaTime;
                }
                else
                {
                    state = AbilityState.Cooldown;
                    cooldownTime = ability.cooldownTime;
                }
                break;
            case AbilityState.Cooldown:
                if (cooldownTime > 0)
                {
                    cooldownTime -= Time.deltaTime;
                }
                else
                {
                    state = AbilityState.Ready;
                }
                break;

        }
    }
}
#
// Ability.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Ability : ScriptableObject
{
    public new string name;
    public float cooldownTime;
    public float activeTime;

    public virtual void Activate(GameObject parent){}
}
#
// Teleport.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[CreateAssetMenu]
public class Teleport : Ability
{
    public float teleportDistance;
    public override void Activate(GameObject parent)
    {
        // teleport towards the mouse cursor position by teleportDistance

        // get the mouse position in world coordinates
        Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        // get the direction from the player to the mouse
        Vector3 direction = mousePosition - parent.transform.position;
        // normalize the direction vector
        direction.Normalize();
        // multiply the direction vector by the teleportDistance
        direction *= teleportDistance;
        // add the direction vector to the player's position
        Vector3 newPosition = parent.transform.position + direction;
        // set the player's position to the new position
        parent.transform.position = newPosition;
    }
}
halcyon monolith
#

is this line 14?

#

Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);

#

or, more importantly, is this the line that the exception is coming from?

ashen delta
#

My bad I should of gone there initially, when I clicked on the error, it sent me to the other line

halcyon monolith
#

I dunno why unity does that

#

I think it's trying to avoid showing you library code

#

but it just dumps you in a bogus location instead

#

you can click the links in the stack trace to jump to the correct line

#

so, this means that Camera.main is null

#

is your camera object tagged MainCamera?

ashen delta
#

I think so

#

actually no

#

That fixed it ty!

halcyon monolith
#

some good reading on this kind of error

#

np!

ashen delta
#

This is probably not the best way to teleport the player towards the mouse anyways, a bit janky. But now I know what I need to fix ty!

halcyon monolith
#

one tip: if you have a rigidbody on the player, you should set its position, rather than messing with the transform's position directly

#

dunno how your game works though