Keith Power
Keith Power

Reputation: 14151

Unity sprite is show before position is changed

I have six or more sprites that are hidden, alpha set to 0. I move the sprites to a starting position at the top of the screen before showing them. Once in the new position I show them and the moving them back to their original positions.

My issue is that the sprites are show just for a couple of milliseconds before they are moved to the starting point. Even though the order of the code is move first then show.

I tried to find a position moved callback to detect when the position change is complete before showing but I don't this it is possible.

void Start() {
        int i = 0;

        foreach (Transform point in drawingPoints.transform)
        {
            //Record points original postion
            Vector3 currentPosition = point.transform.position;
            //Move to new starting position
            point.transform.position = stepOne.transform.position;
            //Now show point
            var color = point.gameObject.GetComponent<SpriteRenderer>().color;
            color.a = 1;
            point.gameObject.GetComponent<SpriteRenderer>().color = color;
            //Move point back to original postion
            point.transform.DOMove(currentPosition, 1f).SetDelay(UnityEngine.Random.Range(0f, 0.3f));

            i += 1;
        }
}

Upvotes: 0

Views: 163

Answers (1)

ChoopTwisk
ChoopTwisk

Reputation: 1334

Consider disabling the sprite renderer till the transform is at the start point.

void Start() 
{
    int i = 0;

    foreach (Transform point in drawingPoints.transform)
    {
        SpriteRenderer spriteRenderer = point.gameObject.GetComponent<SpriteRenderer>();
        if(spriteRenderer == null)
            continue;
        // Disable the renderer.
        spriteRenderer.enabled = false;
        //Record points original postion
        Vector3 currentPosition = point.transform.position;

        //Move to new starting position
        point.transform.position = stepOne.transform.position;
        // Now you're at start point, enable it back.
        spriteRenderer.enabled = true;
        //Move point back to original postion
        point.transform.DOMove(currentPosition, 1f).SetDelay(UnityEngine.Random.Range(0f, 0.3f));

        i += 1;
     }
}

If for whatever reason or weird behaviour of unity you wanna get a callback when something is at a position, here's a hacky way

transformToMove.DoMove(destination, 0).OnComplete(()=>
{
   // Now you're at the point.
});

Upvotes: 1

Related Questions