- Home /
 
               Question by 
               astericaewrites · Nov 15, 2021 at 04:43 PM · 
                unity 2dspriterenderer  
              
 
              How to change a 2d sprite to another sprite in an array?
So I'm recreating an Asteroid clone game, and I'm having trouble in making it so the full asteroid sprite changes to broken up sprites once the player hits it with a laser.
There's no errors or anything when I test, but when the asteroid gets split from the laser, the sprites still shows a full asteroid. I appreciate any help I can get! ty
 public class AsteroidPNG : MonoBehaviour
 {
     public Sprite baseAsteroid; //Full asteroid
     public Sprite[] sprites; //Broken asteroid pieces
     public float size = 1.0f;
     public float minSize = 0.5f;
     public float maxSize = 2.0f;
     public float movementSpeed = 50.0f;
     public float maxLifetime = 30.0f;
 
     private SpriteRenderer _spriteRenderer;
     private Rigidbody2D _rigidbody;
 
     private void Awake()
     {
         this._spriteRenderer = GetComponent<SpriteRenderer>();
         this._rigidbody = GetComponent<Rigidbody2D>();
     }
 
     private void Start()
     {
         //A full asteroid is spawned
         this._spriteRenderer.sprite = baseAsteroid;
         this.transform.eulerAngles = new Vector3(0.0f, 0.0f, Random.value * 360.0f);
 
         this.transform.localScale = Vector3.one * this.size;
         this._rigidbody.mass = this.size;
 
         Destroy(this.gameObject, this.maxLifetime);
     }
 
     private void OnCollisionEnter2D(Collision2D collision)
     {
         if (collision.gameObject.tag == "Bullet")
         {
             if ((this.size * 1.0f) >= this.minSize)
             {
                 CreateSplit();
                 CreateSplit();
             }
             FindObjectOfType<GameManager>().asteroidDestroyed1(this);
             Destroy(this.gameObject);
         }
     }
 
     private AsteroidPNG CreateSplit()
     {
         //This is where the broken asteroid pieces are supposed to show
         GetComponent<SpriteRenderer>().sprite = sprites[Random.Range(0, sprites.Length)];
         this._spriteRenderer.sprite = sprites[Random.Range(0, sprites.Length)];
 
         Vector2 position = this.transform.position;
         position += Random.insideUnitCircle * 0.5f;
 
         AsteroidPNG half = Instantiate(this, position, this.transform.rotation);
         half.size = this.size * 0.7f;
 
         half.setTrajectory(Random.insideUnitCircle.normalized);
 
         return half;
     }
 }
 
               Comment
              
 
               
              Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                