I have a script in my project that relies on getting the size of a sprite renderer component from another object to calculate something.
For testing purposes I have put this object into my scene before but now I want to spawn it using Start() as its size can be different depending on the players setting choices.
The problem I have now is that the script relying on said objects size isn’t working anymore and unity is throwing a “NullReferenceException” error.
Before I was using [SerializeField] MapInfo mapInfo; (The MapInfo script is attached to the other object) and then dragged the sprite with the attached spriterenderer into it in the inspector. But yeah that doesn’t work now. What can I do to solve this?
Little lost in what is where, but dragging objects into SerializeFields is not limited to objects in the scene, you can drag your prefabs into those slots as well.
I am trying to reference the SpriteRenderer of a GameObject that was created during runtime in my code. I added the SpriteRenderer to that GameObject during runtime as well.
I then want to get the size of that SpriteRenderer to do some calculations with it.
But whenever I try to reference this SpriteRenderer I get a “NullReferenceException”.
Last thing I tried was creating a private variable at the top of my class and then do this:
If you added the SpriteRender to the object during runtime, then you already have a reference.to the object.
Since you had the object in your Scene before, I assume it is, or can be a prefab object.
Object 1 has the script attach to it.
The script can have the SerializeField MapInfo like you had before.
In the editor drag the Mapinfo prefab, object 2, into the Serialize field
In your script you can use the name of the SerializeField, MapInfo wherever you want.
For example, to spawn the prefab using
Instantiate(MapInfo, new Vector3(1, 2, 1), Quaternion.identity);