Moving Object A to random position of other X objects

  android, button, c#, unity3d

Here is what i want to do, this is supposed to work something like a hint button. When clicked on Object A, which is a loupe, it is supposed to move to random position of one of X hidden objects and then return after like 3 seconds. Here is what i tried:

public class Lupica1 : MonoBehaviour
{
    //List of positions
    public Transform[] positions;
    //Just holds the index of picked random position
    private int br;
    private Transform target;
    private float speed = 1f;
    private Vector3 OrgPos;
    private float timer = 3f;


    // Start is called before the first frame update
    void Start()
    {
        //Stores the original of position of ObjectA(loupe)
        OrgPos = gameObject.transform.position;
        //Index of random position is picked here
        br = Random.Range(0, positions.Length);
        //And stored into target
        target = positions[br];
    }

    // Update is called once per frame
    void Update()
    {
        //Timer 
        timer -= Time.deltaTime;
    }
    
    //This is the method to assign to onClick function in Inspector 
    public void Lupica()
    {   
        
        transform.position = Vector2.MoveTowards(gameObject.transform.position, target.transform.position, speed * Time.deltaTime);
        //When timer reaches 0, return object A(loupe) to original position
        if (timer < 0)
        {
            gameObject.transform.position = OrgPos;
        }

    }
}

Source: Android Questions

LEAVE A COMMENT