How do I get transform coordinates of an object?

I feel like I am either missing something extremely simple or managed to completely misunderstand how to use properties. Long story short I want to get the Y coordinate of an object as a float through the transform component and tried to use debug.log to confirm if it works. This is the current code:

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

public class LaneScript : MonoBehaviour
{
public float y;
public Transform t;
void Start()
{
y = t.position.y;
Debug.Log(“I’m at coordinate y” + y + “!”);
}

}

This was the result of trying to find answers by myself, and while I finally got something that doesn’t show an error in Visual Studio itself Unity says that “Object reference not set to an instance of an object”. I tried but couldn’t find a way to make the script know that I’m referring to the object the script is attached to. What am I doing wrong?

While I doubt this is relevant I will also add that this is a 2D project, the script is attached to a prefab and said prefab was added multiple times to the scene. There are no components in the prefab other than Transform, Sprite renderer and the script I showed above.

It doesn’t matter what you’re doing, and this error NEVER requires a forum post.

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.

You need to figure out HOW that variable is supposed to get its initial value. There are many ways in Unity. In order of likelihood, it might be ONE of the following:

  • drag it in using the inspector
  • code inside this script initializes it
  • some OTHER external code initializes it
  • ? something else?

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

https://discussions.unity.com/t/814091/4

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

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

https://discussions.unity.com/t/840647/7

1 Like

Thanks a lot, I mean it. I will remember this whenever I encounter this specific error message again.

1 Like