UI Object Random Movement in Unity 3D

It’s a common requirement in designing GUI in Unity to move & animate few UI Game Objects randomly over the screen. Following C# Script will help you in UI object random movement in Unity 3D & 2D. You can attach this script to any UI object which you want to move randomly over the screen.

UI Object Random Movement in Unity
Food vector created by upklyak – www.freepik.com

It is assumed that the name of your canvas in the objects hierarchy is “Canvas”.

C# Script for UI Object Random Movement in Unity

using UnityEngine;

public class UIObjectRandomMovement : MonoBehaviour
{

    RectTransform canvas;
    RectTransform currentObj;
    public float speed;
    float horizontalSpeedMultiplier = 1f; // +1 moves right, -1 moves left
    float verticalSpeedMultiplier = -1f; // +1 moves upward, -1 moves downward

    void Start()
    {
        currentObj = gameObject.GetComponent<RectTransform>();
        canvas = GameObject.Find("Canvas").GetComponent<RectTransform>();
    }

    void Update()
    {
        transform.Translate(horizontalSpeedMultiplier * speed, verticalSpeedMultiplier * speed, 0f);

        if (currentObj.position.y > canvas.rect.height)
        {
            verticalSpeedMultiplier = -1f; // now start moving downward
        }

        if (currentObj.position.y < 0f)
        {
            verticalSpeedMultiplier = 1f; // now start moving upward
        }

        if (currentObj.position.x < 0f)
        {
            horizontalSpeedMultiplier = 1f; // now start moving towards right
        }

        if (currentObj.position.x > canvas.rect.width)
        {
            horizontalSpeedMultiplier = -1f; // now start moving towards left
        }
    }
}

You can set any float value as a Speed. 2.0f is the normal speed. When horizontalSpeedMultiplier is +1 object will move towards the right and in case of negative 1 will move towards the left. When verticalSpeedMultiplier is -1 it will move downwards and in case of +1 will move upward. That’s it 🙂

Here you can find many other Helping code Snippets & Tutorials.

Please share this post:
Native Mobile Application Developer (Android + IOS) having experience in Java, Swift, Kotlin, Objective C, Unity, C#, C/C++, NODE JS & PHP.

Ask a Question

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

%d bloggers like this: