Search Unity

Instantiated prefab object following Player if SpriteRenderer's alpha is modified

Discussion in '2D' started by Strobosaur, Jul 15, 2022.

  1. Strobosaur

    Strobosaur

    Joined:
    Aug 17, 2020
    Posts:
    1
    So i'm making a simple pixel art 2d platformer. During a certain player action i want to create a trail of circles after him. I have a prefab object for this, which contains a SpriteRenderer, and a Script.

    The problem is that all of the instantiated prefabs follow the player transform like if they were child objects (they're not). The weird thing is that if i comment out the line that modifies the Flash prefabs SpriteRenderer alpha value,

    "sr.color = new Color(sr.color.r,sr.color.b,sr.color.g, sr.color.a * (factor * Random.Range(0.25f,0.75f)));"

    it does make a trail like i want, and every clone object stays at the position it was instantiated...

    This is the relevant code:

    Code (CSharp):
    1. public class Flash : MonoBehaviour
    2. {
    3.     public SpriteRenderer sr;
    4.     private float duration;
    5.     private float factor;
    6.     private float startTime;
    7.  
    8.     private void Start()
    9.     {
    10.         transform.parent = null;
    11.         transform.Translate(Random.insideUnitCircle * 0.325f);
    12.         startTime = Time.time;
    13.         duration = Random.Range(1f,3f);
    14.     }
    15.  
    16.     private void Update()
    17.     {
    18.         factor = Mathf.Max(0f, 1 - ((Time.time - startTime) / duration));
    19.         sr.color = new Color(sr.color.r,sr.color.b,sr.color.g, sr.color.a * (factor * Random.Range(0.25f,0.75f)));
    20.  
    21.         if (Time.time - startTime > duration) {
    22.             Destroy(gameObject);
    23.         }
    24.     }
    25. }
    The SpriteRenderer sr is set to be the prefabs own SpriteRenderer in the editor. The prefab is instantiated in the following code in the PlayerController script:

    Code (CSharp):
    1.     protected void FlashTrail(Vector2 flashPos)
    2.     {
    3.         if (Time.time - lastFlash > flashRate){
    4.             Instantiate(flashPrefab, new Vector3(flashPos.x, flashPos.y, 0f), Quaternion.identity);
    5.             lastFlash = Time.time;
    6.         }
    7.     }
    Code (CSharp):
    1. protected void Update()
    2.     {      
    3.         if (isAttacking){
    4.             FlashTrail(new Vector2(transform.position.x, transform.position.y));
    5.             if ((Time.time - lastAttack > attackDuration) || (Vector2.Distance(transform.position, attackTarget) < 0.25f)) {
    6.                 isAttacking = false;
    7.             }
    8.         }
    9.     }
    I'm fairly new to Unity and i really have no clue o_O Anyone that can point me in the right direction?

    Thanks a lot!