Making reusable functions in Unity

Posted on

in

,

One of the core fundamentals of programming. Here’s an example:

public void randomX(GameObject obj){
        GameObject wall = GameObject.Find ("wallLeft");
        Vector2 fullScreen = Camera.main.ScreenToWorldPoint(new Vector2(Screen.width,Screen.height));
        //world point calculations
        float wallWidth = wall.GetComponent<Renderer> ().bounds.size.x;
        float objWidth = obj.GetComponent<Renderer> ().bounds.size.x;
        float widthRange = fullScreen.x - wallWidth-objWidth/2;

        float ranX = Random.Range (-widthRangewidthRange);
        obj.transform.position = new Vector2 (ranXobj.transform.position.y);
    }

This function gives a game object a random x position on the screen. It takes into consideration padding on the sides (in this case, a wall on both sides) as well as the width of the object itself so half of it doesn’t get stuck in the wall.

To use this function use:

randomX(someGameObject);

You can insert any game object inside the brackets. To use this in another script follow this example to draw the code into the current script and then use

 newInstanceName.randomX(gameObject);

‘newInstanceName’ is the instance name where the original code sits and ‘gameObject’ simply chooses the game object that the current script is attached to. Note the lower case g, as ‘GameObject’ refer to the type game object.

 

Leave a Reply

Your email address will not be published. Required fields are marked *

About me

Mark Wong is a front end developer with 10+ years experience. Most of his knowledge of HTML5, CSS and Js is self taught.

Calendar

July 2024
M T W T F S S
1234567
891011121314
15161718192021
22232425262728
293031