Anonymous Gaming Anonymous Gaming - 1 year ago 112
C# Question

C# Unity - Preventing The Player From Standing on a Certain Terrain Texture

I am wondering how to prevent the player from walking on a certain texture on the Unity terrain. I have made the script that detects on which texture the player is standing on. For the movement I use the rigidbody velocity so I don't have problems with colliders. Thanks in advance :)

Answer Source

I would do something like this:

First, create the global variable lastPos:

Vector3 lastPos;

Then set it to the players current position on Start:

void Start() {
  lastPos = player.gameObject.transform.position;

Then in Update, set the lastPos variable to the players current position. Next, use an if statement to check if the player is on an invalid texture. If the player is on an invalid texture, set it's position back to lastPos:

void Update() {
  if (playerOnInvalidTexture) {
    player.gameObject.transform.position = lastPos;
  lastPos = player.gameObject.transform.position;

Essentially this places the player at a valid position when on an invalid texture.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download