This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 5 months ago.
So i am trying to make a simple gameobject saving system in Unity.
Whenever i place an cube i enter it in a GameObject called currentCube
GameObject currentCube = new GameObject();
currentCube = Instantiate(CubeBlue, placeLocation, new Quaternion());
This places my cube all good and well. Then just for debugging i check if the currentCube actually has the just placed Cube
print(currentCube.transform.position);
This does indeed give the location of my newly placed Cube. But then i try to add the cube to a List (also tried with an array)
cubes.Add(currentCube);
But then i get a NullReferenceException
NullReferenceException: Object reference not set to an instance of an object
And then with the Script filename and the location line of where i put the "cubes.Add(currentCube;)"
EDIT:
Also in my part above the void start i have stated
private List<GameObject> cubes;
Looks like your List is not getting Initialized. Try
private List<GameObject> cubes = new List<GameObject>();
Related
This question already has answers here:
How to access a variable from another script in another gameobject through GetComponent?
(3 answers)
Closed 25 days ago.
I am in no way a coding novice but I just picked up unity and I'm trying "get it"
My question involves this code. it is not part of an active project. it is simply an attempt to understand the system
private SpriteRenderer beans2;
public Sprite beanimmage;
// Start is called before the first frame update
void Start()
{
beans2 = gameObject.GetComponent<SpriteRenderer>();
beans2.sprite = beanimmage;
}
from what I understand this code allows me to manipulate the SpriteRenderer of the game object this code is attached to by assigning it to beans2 and then changing the Sprite of beans2 to beanimmage and works fine in the system
My question is -
Is their a way to assign beans2 to the spriterenderer of a diffident game object? The object i have this code attached to is just a game object called test is their a way to assign the beans2 variable to the SpriteRenderer of my test2 object instead ?
something like this ?
beans2 = test2.gameObject.GetComponent<SpriteRenderer>();
beans2 = gameObject.test2.GetComponent<SpriteRenderer>();
The GetComponent() Function is apart of every gameobject so to get components on other gameobjects you need to reference that gameobject in a variable, something like this:
public GameObject test2;
private SpriteRenderer test2Renderer;
public Sprite beanImage;
void Awake()
{
test2Renderer = test2.GetComponent<SpriteRenderer>();
test2Renderer.sprite = beanImage;
}
Alternatively, you can just get the component of the test2 object from the inspector because you are using public variables. To do this make a sprite renderer variable field and make it public so it is shown in the inspector, then drag the test2 object into the field and it will automatically get the sprite renderer component off that object.
Finally, you could also just do this with one field. This method would be used when you only want to access the GameObject and nothing else:
public GameObject test2;
public Sprite beansImage;
void Awake
{
test2.GetComponent<SpriteRenderer>().sprite = beansImage;
}
Any way works and you should do it the second way if you want to work with public variables and rely on the inspector but if you only need the gameobject then go with method 3. Method 1 is probably the best way to do it so you can change the sprite later if you want.
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
In Unity (C#), why am I getting a NullReferenceException and how do I fix it? [duplicate]
(1 answer)
Closed 1 year ago.
I have an enemy AI script working that basically follows my player. Right now I have a "public GameObject player" that I have to assign manually by dragging my player prefab onto the slot. But I want to have a lot of enemies in the scene, so I don't want to have to do this manually for each one. How Can I give the EnemyController script a default player to follow?
I have a PlayerManager which I use to pass the position of my player to the enemy with:
public class EnemyController : MonoBehaviour
{
Transform target;
// Start is called before the first frame update
void Start()
{
target = PlayerManager.instance.player.transform;
}
That part works fine. So my thinking was, just make a public variable for the player like this:
public GameObject player = PlayerManager.instance.player;
But that didn't work. I got this error: "NullReferenceException: Object reference not set to an instance of an object"
Thank you so much for any help you can provide!
With public GameObject player = PlayerManager.instance.player; your field is initialized before the call of EnemyController's constructor, and you provided no control over the value / definition state of PlayerManager.instance.player (PlayerManager or instance or player which can be null and is null in your case). So it's "too early" to use it.
Instead, you can use the event playerJoinedEvent in the PlayerInputManager to assign the enemy to the played which just joined with an event handler, which checks that PlayerManager and instance and player are not null and then assign the player to the target.
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 2 years ago.
There are 3 Scripts at play in the problem I am experiencing.
Firstly I have an object which I whish to select which the following code to comunicate with the "GameManager"(the secound relavent object) that it is the selected object this works:
public void OnMouseDown ()
{
if(TheGameManager.SelectableOn || TheGameManager.SelectedObject == this){
//If clicked and not already selected then determain this as the selected object
OnOff = !OnOff;
if(FindObjectOfType<GameManager>().SelectedObject != this){OnOff = true;}
if(FindObjectOfType<GameManager>().SelectedObject == null){OnOff = true;}
//Determain this as the selected object
if(OnOff){FindObjectOfType<GameManager>().SelectedObject = this; TheGameManager.UpdateZUIInterface("close");}
else{FindObjectOfType<GameManager>().SelectedObject = null;TheGameManager.ResetAllUIToDefault();}
TheGameManager.UpdateAllUIElements();
}
This is how it looks in the inspector
Picture of the first object being selected
The problem occures however when I try to reference this instance safed within the GameManager.
[SerializeField] GameManager TheGameManager;
public void OnMouseDown (){
Selectable SelectedObject = TheGameManager.ProvideSelectedObject();
Debug.Log(SelectedObject.gameObject);
Debug.Log(TheGameManager.SelectedObject.GetComponent<Selectable>().gameObject);
}
Neither of these two ways to acces the instance works. I could imagine a direct reference send from the instance itself would work however I try to use the GameManager as a central storage of most of the frequently uses variables so i would like to avoid doing that. Do any of you have any solution or thoughts?
I would love to hear from you.
If the TheGameManager is setup as a Singleton, then it likely has a static instance property or field. In that case, you should be calling the static isntance field instead of a local instance of the TheGameManager
So, remove:
[SerializeField] GameManager TheGameManager;
And now call the game manager like this:
varSelectedObject = TheGameManager.instance.ProvideSelectedObject();
This is supposition, but I dare say it's the cause of your problems. If this isn't the case, we'll need to see the actual code for TheGameManager.
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 2 years ago.
This is one of the most frequent questions asked by beginners using Unity so I'm asking it one more time to address the Unity-specific causes not fully answered by the canonical NullReferenceException question.
I'm working on a game in Unity and when I hit play, I got an error that says "NullReferenceException: Object reference not set to an instance of an object" and I can't figure out why it's happening. What is causing it and how do I fix it?
Explanation
In C# generally, this is caused by referencing a field that hasn't been initialized. For example, if you have a field public List<GameObject> items and you later call items.Add(foo) without first doing items = new List<GameObject>(), then you are trying to add an item to a list that doesn't exist.
However, in Unity specifically, this is most frequently caused by forgetting to set a reference in the inspector. When you create a new component and add a field public Transform destination, then you most likely are intending to assign a prefab in the inspector. If you forget, you're trying to reference something that doesn't exist.
Solutions
If you double-click on the error message in the console window, Unity will (with a few exceptions) highlight the GameObject in the hierarchy that threw the error, and open your code editor and highlight the line of the script where the error occurred.
If you are using any of the Find-like methods to get the GameObject, be sure that the GameObject is active, otherwise Find-like methods will return null or may return the wrong GameObject. If you need the GameObject to be inactive when it is found, you need to use a different way of getting a reference to the GameObject than using a Find-like method to find the GameObject directly, such as having the component register with a Manager-type class.
Looking at the GameObject, make sure you've assigned everything in the inspector that should be assigned.
If everything has been assigned, run the game with the GameObject that threw the error selected. It's possible that you have something in Awake() or Start() that's negating the reference, and you'll see the inspector switch to None.
Pay attention to the return types of methods you use to modify objects. For example, if you call GetComponent() or anything similar on an object and the component is not found, it will not throw an error. It will just return null. This can easily be handled with a line like:
if(thing == null) //log an error, or do something to fix the reference else //do what you wanted to do
That should cover the most frequent Unity-specific causes. If that still isn't fixing your issue, Unity's own page on NullReferenceException, and for C# generally, there's a more in-depth explanation of NullReferenceException in this answer.
This question already has answers here:
Accessing a variable from another script C# [duplicate]
(3 answers)
Closed 6 years ago.
I have 2 c# scripts in my game. On of them is in my "main player object" and the other script is in "my main camera". I want to declare a float variable in the script of my main player, and in every game second i want to record the x position of my player in that variable and at the same time passing this value to the my main camera's script and assigning this value into the x position of my main camera in every game second. How can I pass a variable to a script from another one ? Or how can i create a variable which can be used by any script in my game ?
There's an answer here that explains this problem in great detail, but the simplest way that is included in that answer would be to do something like the following:
public class Speed: MonoBehaviour
public float speed;
// maybe you want restrict this to have read access, then you should use a property instead
And then in other scripts:
GameObject gameObject = GameObject.Find ("Some object");
Speed theSpeed = gameObject.GetComponent <Speed> ();
float mySpeed= theSpeed.speed;