< Back to Game Dev, Unity

Making reusable functions in Unity

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.

 

Be Sociable, Share!

Leave a Reply

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