I'm trying to make something move in unity and change direction in random intervals.
I have the idea of creating public bools for each movement (2D) right, left, up, down, and make the machine choose one of them to be true and the others false at random time intervals.
Note that what you are looking for and what your goal is don't seem to align, but implementing such value is entertaining in itself.
First of all, you definitely can't change true
to anything (similar to changing number 1
to 42
) - there are languages/runtimes where such thing is possible at compile time ( #define true 0
) or at run-time time (not-so-compliant Fortran or hacking up interned values in Python), but it is not a good idea in general and not really possible in C#.
Since we can't change literal values there are 3 options to implement that functionality - fields, properties and separate class either directly or via captured variables. Since fields by themself can't have logic and hence can't change own value - it requires some code to manipulate them making "become false" code with fields essentially equivalent to properties.
So our goal is to have a property that changes value after random interval:
var currentValue = this.MyValueProperty;
Now we need a "random" interval (for simplicity code uses well known random number , for your code look up Unity3d Random ) and some sort of "current time" to see if value needs to switch from true to false (and vice versa).
bool myValueField = true; // stores current value
int timeToChange = 0;
public bool MyValueProperty =>
{
int currentTime = GetCurrentOrGameTime(); // pick your time here
if (timeToChange < currentTime)
{
// time to flip the value and update next time to change
myValueField = !myValueField;
// random value here in the range you like GetRandom(10,100)
int randomInterval = 4; // code uses well known random number
timeToChange = currentTime + randomInterval;
}
return myValueField;
}
Notes:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.