- Home /
How to Instantiate Sprite Prefab C#? - [SOLVED]
Hello all, I have been struggling with what I thought would be a very trivial concept, and it has proven to be quite frustrating.
So, I am trying to create a simple 2D game right now in which you control a character that can shoot spells of some sort. Currently, I am having trouble instantiating prefabs of a fireball spritesheet.
I have used the sprite importer / editor to slice up my sprite sheet into appropriately-sized sprites.
I then dragged all of the sprites I planned on using onto to the Game screen, then dragged them all into the Prefabs folder so that their names turned blue and became prefabs.
I then have a script on an empty game object called SpellSpawner that has a public array of GameObjects called spells[] which I have set to 3. I dragged 3 of the prefabs I wanted to use into each individual game object spot in the list. However, whenever I try to call or instantiate an object from the list (e.g. spells[0]) it gives me a null reference error.
Could anyone help me understand what I am doing wrong? Here is my code: using UnityEngine; using System.Collections;
public class SpellCast : MonoBehaviour {
//reference to hero
private GameObject hero;
private HeroControl control;
//array to hold particles for different spells
public GameObject[] spells;
void Start () {
hero = GameObject.Find ("hero");
control = (HeroControl) hero.GetComponent (typeof(HeroControl));
}
// Update is called once per frame
void Update () {
if (Input.GetButtonDown ("Fire1") && control.facing == "right") {
GameObject spellBolt;
spellBolt = Instantiate(spells[0], transform.position, transform.rotation) as GameObject;
spellBolt.transform.position = transform.position;
}
}
}
And here is a picture of the whole situation in Unity:
Aaaaand now I feel like an idiot haha. Thank you so much. I swear these little syntax errors get me 90% of the time.
Ins$$anonymous$$d of rena$$anonymous$$g the question and just adding "[solved]" at the end, you should close it.
Answer by Malfegor · Apr 14, 2014 at 06:58 PM
Try capitalizing the 'h' in your hero = GameObject.Find("hero"). So try making it 'hero = GameObject.Find("Hero")'. Maybe your hero is just null?