Hello, I have a gameobject that when it collides with something for it to move towards a position. but I would like it to move towards a random position (which is in this script “rightpos”) higher than the gameobject current position. How would I go about doing this?
I used Vector3? instead of Vector3. This is called a nullable type. You can use it on every variable type you want. It has all of the properties of the type, be it can be assigned the null value. Here, I find it practical because it avoids having 2 variables (one for the position, and one boolean to know if the position has been set).
I added an OnCollisionExit2D that sets the position to null so that if the object leaves the collider, it no longer moves. I don’t know if that’s what you want, but it illustrates my previous point; I can set rightpos to null.
I put the border tag at the beginning of the script so if one day it has changed, you don’t have to scroll through the script to find the hardcoded value in the middle of something. It also avoids human errors, because having to type “Border” each time you want to check the tag of a GameObject is error-prone.
I added an IsBorder method so if one day you change the way you decide what is a border and what is not, you just have to do that in there and not in other random places of the code.
The GetRandomPositionAbove uses Mathf.Abs so that even if you input a negative value as the offsetY argument, it still considers it a positive value. The method name contains “Above” so it has to do what it says and can’t return a position below.
You can see that GetRandomPositionAbovePlayer calls GetRandomPositionAbove, which is directly below, and GetRandomPosition which is again directly below. That way, we you read the script, it reads like a story: you read from top to bottom, and the implementation details appear one by one. Once you’ve found what you were looking for, you know you don’t have to read further to be sure you’ve not missed something important. This technique is called “The stepdown rule”.
More generally, I like keeping my methods short so the whole system is easier to read and to debug. Plus, it adds extra functionality that you could need later in the development.