So I'm setting up a prefab for a tree, which will spawn and scroll down the page. It's spawning is managed in another script, but the thing I'm trying to do in this script is get it to randomly choose a sprite from it's sprite-sheet and then apply itself as well as it's shadow.
Here is my code:
public Sprite[] Trees;
// a public value which can be edited outside the script. This will dictate the object's speed.
//Must be replaced later with a reference to speedcontroller object.
public float speed = 5.0f;
// Use this for initialization
void Start () {
//This generates a random number which dictates the sprite.
int spriteRandomizer = Random.Range (1,5);
int spriteIndex = spriteRandomizer - 1;
//These if statements replace the sprite based on the Random value generated for both the Tree and it's Shadow.
if(spriteRandomizer == 1) {
this.GetComponent<SpriteRenderer>().sprite = Trees[spriteIndex];
this.gameObject.transform.GetChild(0).GetComponent<SpriteRenderer>().sprite = Trees[spriteIndex];
}
if(spriteRandomizer == 2) {
this.GetComponent<SpriteRenderer>().sprite = Trees[spriteIndex];
this.gameObject.transform.GetChild(0).GetComponent<SpriteRenderer>().sprite = Trees[spriteIndex];
}
if(spriteRandomizer == 3) {
this.GetComponent<SpriteRenderer>().sprite = Trees[spriteIndex];
this.gameObject.transform.GetChild(0).GetComponent<SpriteRenderer>().sprite = Trees[spriteIndex];
}
if(spriteRandomizer == 4) {
this.GetComponent<SpriteRenderer>().sprite = Trees[spriteIndex];
this.gameObject.transform.GetChild(0).GetComponent<SpriteRenderer>().sprite = Trees[spriteIndex];
}
}
// Update is called once per frame
void Update () {
//object immediately begins to "fall" down the screen/towards the player, based on pre-defined speed.
transform.position += Vector3.down * speed * Time.deltaTime;
}
}
This is for Uni, so the annotation is partially for me, partially for the Tutors. This is the first game I've tried to make outside of the course I followed on Udemy, so be kind, I'm sure there are a million better ways to do this, I just want to fix my error and get this to work.
This is the error I'm getting: IndexOutOfRangeException: Array index is out of range. TreeScript.Start () (at Assets/Scripts/TreeScript.cs:27)
Aucun commentaire:
Enregistrer un commentaire