- Home /
Question by
dbubbis · 4 days ago ·
charactercontrollercollision detectioncharacter controller
If-statement not working on certain gameObjects,Transform.Position not working anymore on gameObject except in one if-statement.
For some reason, whenever I use an if-statement on gameObjects besides one of them, the entire if statement except for when I try to change the player's position works. Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Threading;
public class detectcollision : MonoBehaviour
{
public GameObject tplocation1;
public GameObject player;
public GameObject entranceloc;
void OnControllerColliderHit(ControllerColliderHit hit)
{
//This if statement does Debug.Log the message and it also changes the player's position.
if (hit.gameObject.name == "trigger")
{
Debug.Log("triggered");
gameObject.transform.position = tplocation1.transform.position;
Thread.Sleep(7);
Application.Quit();
}
//This if statement does not change the player's position, but Debug.Logs the teleporting message.
if (hit.gameObject.name == "entrance")
{
gameObject.transform.position = new Vector3(-3184.53f, 20.35f, -171.585f);
Debug.Log("teleporting...");
}
}
}
,This problem is very unusual, and I really need this to be fixed soon. Here is my code where I am trying to change the player's position:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Threading;
public class detectcollision : MonoBehaviour
{
public GameObject tplocation1;
public GameObject player;
public GameObject entranceloc;
void OnControllerColliderHit(ControllerColliderHit hit)
{
//This if statement does Debug.Log the message and it also changes the player's position.
if (hit.gameObject.name == "trigger")
{
Debug.Log("triggered");
gameObject.transform.position = tplocation1.transform.position;
Thread.Sleep(7);
Application.Quit();
}
//This if statement does not change the player's position, but Debug.Logs the teleporting message.
if (hit.gameObject.name == "entrance")
{
gameObject.transform.position = new Vector3(-3184.53f, 20.35f, -171.585f);
Debug.Log("teleporting...");
}
}
}
Comment
Answer by Deuce2008 · 4 days ago
If you are using a character controller, it won't work. character controller don't respond well to having there transforms changed. To fix this is to first disable the character controller, teleport the player, then enable the character controller.
Example:
void TeleportPlayer(Vector3 position)
{
//Get the charecterController attached to this gameobject
CharacterController controller = GetComponent<CharacterController>();
//Disables the controller
controller.enabled = false;
//Teleports this object to the position specified when this function is called
transform.position = position;
//Enables the controller
controller.enabled = true;
}