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.
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 1 year ago.
This error happened after I closed the unity (I saved everything), the other day I opened it and the error came up.
I tried to create prefabs and I was unable to use the debug log as mentioned in some topics.
public void Show()
{
animator.Play("FadeInUI");
cv.interactable = true;
cv.blocksRaycasts = true;
}
void Start()
{
isGameRunning = false;
gameStartUI.Show();
}
Error
Here is the error
Everything is assigned as it was in the video and as it was the day before, I just opened it and the error appeared.
A possible explanation is that Unity is calling your GameController's Start() before your GameUI's Start();
One way to fix this is by moving the GetComponent call from the Start method to the Awake method. GetComponent calls (as well as any other reference-getting operation like GameObject.Find()) are usually done in Awake, as every Awake is called before any Start method. See this page for more info.
Another way would be to use this attribute to explicitly tell Unity which order to run your scripts in.
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.
I am working with triggers in Unity3d. I have a reference to another object that enters the trigger, and if that object has a variable that is set to a value, then I want to call its own method.
Something along the lines of:
if(gameObject.hasAttribute('canDance') == true)
{
gameObject.dance();
}
What is the correct code to perform such an action?
You need a reference to the script attached to the GameObject. I will assume you already found the GameObject and hold a reference to it named myGameObject. If you don't know how to find it, you can do this:
GameObject myGameObject = GameObject.Find("Name Of GameObject in Scene");
Now to grab the script you can do this:
ScriptName script = myGameObject.GetComponent<ScriptName>();
Then you can make calls to the functions inside the ScriptName class like this:
script.functionName();