Hello all,
This is my first post / question here and I’m sure there will be many more. I’ve been using Unity for a while now and have figured out everything on my own ( with some help from these forums ), but now I’ve been stuck on a few things for a little while now that I haven’t been able to figured out.
I have several prefabs that I use for spells in my game. Fireball, lightning bolt, freeze etc. I have particle emitters and scripts attached to each. I have a variable called currentSpell which is of type Transform. Any time I try to assign any of the prefabs to this varible – through code – I get no error in the editor, but the prefab doesn’t get assigned. I can see that in the inspector after I assign it. It never changes and the following code bombs;
or even this.currentSpell = LightningBoldPrefab; (which I knew wouldn’t work anyway)
I get “Unknown identifier: ‘LightningBoldPrefab’”
I have several little issues I’m trying to work through on my own, but this one has me totally stumped. Any help saving my sanity would be greatly appreciated
Well firstly, by explicitly saying currentSpell is of type transform, LightningBoltPrefab must be too, although it is a prefab, which is a GameObject. Also, your code/explanation doesn’t make much sense : /. Not to me at least. When you instantiate something you create it, but in the line before that you use GetComponent which means it should already be a part of the current gameObject…? If it isn’t already part of the current object, then GetComponent will return null and in turn currentSpell = null. So your problem is really that you’re trying to use GetComponent when it isn’t a component of the current gameObject, it’s a prefab that hasn’t been referenced anywhere.
One option would be to have an array of GameObjects, call it spells.
spells : GameObject[ ];
Fill this in the inspector with your spell prefabs in a known desired order, and when you want to instantiate each just Instantiate(spells*, …), when i = the index of the spell you want. Does this help? Check the Docs on GetComponent and Instantiate. Let me know if that helps lol.*
Actually the post was a typo Not sure what the heck I was thinking when I typed that up, but I went back to the code and double check just to make sure The actual code is correct.
Thanks, enragedmrt. Your direction was what I needed, in this case. I was under the impression that GetComponent() by itself would get a reference to an object that wasn’t attached to anything. Just pull it from the project and after Instantiate() be able to access it. I was wrong Now I understand it better after your explanation followed by re-reading the docs on it.