how to assign the player as a prefab (C#)

I’m trying to assign the player as the variable, but when ever i make the variable public and reference the player prefab, unity throws a null reference exception.

even when I tried using “FindGameObjectWithTag” it didn’t work

public bool isTargeted;
    GameObject Player;
    void Start()
    {
        timer = lifeTime;

        //Player = GameObject.FindGameObjectWithTag("Player");

        if(!isTargeted) {
            transform.rotation = Quaternion.Euler(0, 0, rotation);
        }
        if(isTargeted) {
            transform.LookAt(Player.transform);
        }
    }

Are you sure this is what gives you the exception? If you have it assigned in the editor (preferably with [SerializeField], not public), then it should work just fine, and if you don’t, that’s not even a nullref. Can you tell exactly what line this exception is on?

1 Like

From your post it is unclear if you intend to publicly define and assign the Player in the editor, or if you are hoping to find it at runtime via some method such as tags or whatever.

Before you write another character of code, you need to decide on ONE approach. Both approaches will not work well together.

I suggest the former approach: make it public, drag a reference in, save the scene / prefab… DONE. Never again worry about it.

For your reference, whenever you see a nullref, there is only ONE process to go through:

The answer is always the same… ALWAYS. It is the single most common error ever.

Don’t waste your life spinning around and round on this error. Instead, learn how to fix it fast… it’s EASY!!

Some notes on how to fix a NullReferenceException error in Unity3D

  • also known as: Unassigned Reference Exception
  • also known as: Missing Reference Exception
  • also known as: Object reference not set to an instance of an object

http://plbm.com/?p=221

The basic steps outlined above are:

  • Identify what is null
  • Identify why it is null
  • Fix that.

Expect to see this error a LOT. It’s easily the most common thing to do when working. Learn how to fix it rapidly. It’s easy. See the above link for more tips.

This is the kind of mindset and thinking process you need to bring to this problem:

Step by step, break it down, find the problem.

Here is a clean analogy of the actual underlying problem of a null reference exception:

1 Like

I got it to work, but now when ever I hit play the objects sprite is gone, and weird stuff happens

using UnityEngine;

public class LookAtPlayer : MonoBehaviour
{
    public Transform Player;

    void Update() {
        transform.LookAt(Player);
    }
}

I’m so confusion