I am having some issues type casting to a GameObject.
Basically, I have this line of code:
GameObject cell = Resources.Load("Cell") as GameObject;
where Cell is a public class located in the Assets/Resources folder.
If I run this code, it throws an error farther down in the code saying that cell points to null (Null Pointer Exception).
To make sure that this line was the problem, I added the following directly after the above line:
if(cell == null)
Debug.Log("NOOOO!");
After running it again, I saw the “NOOOO!” log message in the system log, confirming that that line was the culprit.
What am I doing wrong?
I should also note, that if I change the first line of code to the following:
Object cell = Resources.Load("Cell");
It does, indeed, load the resource.
Is it not possible to type cast an Object to a GameObject?
What if you try:
Object cell = Resources.Load("Cell") as GameObject;
Works?
No, sir. It gives me the same error as the first line.
When I think of it, if this is indeed a script you are trying to recast, then it may not be possible.
Hmm… I see… I was afraid of that.
Well, in that case, how can I go about instantiating a GameObject that has the properties of that script?
Instantiate a prefab with the script on it. That should get you somewhere. Of course, depending on exactly what it is you are doing, you would need to know yourself how to implement the specifics.
Creating a prefab and doing recasts and such on it works fine though, compared to the script recast, for what it’s worth.
GameObject cellObject = new GameObject();
Cell cellScript = cellObject.AddComponent();
Thanks guys, but I got it working. I took an entirely different approach in the rest of my code that allowed me to do what I wanted without instantiating a script as a game object.
And Antitheory, that wouldn’t work because the way I was doing things, I couldn’t allow my script to inherit from MonoBehaviour.
It makes things even easier:
Cell cell = new Cell(…);
Not really. Sure, that instantiates the class, but it wouldn’t be instantiated as a GameObject. That was the whole point.