We want to rotate an object when we stand on it, but as soon as we stand on it unity crashes (we think because it is too much rotations to handle when we do it in a loop:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Teleportation : MonoBehaviour {
public GameObject Portal;
public GameObject Player;
private Transform tf;
public int tpDelay;
private GameObject pentagram;
void Start()
{
pentagram = GameObject.FindWithTag("Pentagram");
tf = pentagram.GetComponent<Transform>();
}
public void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Player")
{
StartCoroutine (Teleport ());
Rotate();
}
}
void Rotate()
{
while (true)
{
tf.Rotate(new Vector3(0, 0, 6));
}
}
IEnumerator Teleport()
{
yield return new WaitForSeconds (tpDelay);
Player.transform.position = new Vector2 (Portal.transform.position.x, Portal.transform.position.y);
}
}
You should watch the Unity basics tutorials, and also some C# coding tutorials for general logic…
Your rotation method won’t work - you are basically saying “while something is true” (which is always, as your condition is simply “true” and not a condition (like x < 10 or something).
So you are starting a while loop once in OnTriggerEnter2D and it will run forever in that loop after that (= stuck).
If you need some continuous animation, movement or rotation (or anything continuous that doesn’t happen at once / one time) you’ll have to do it in Update, FixedUpdate or LateUpdate, depending on your needs. This way you can run something one step at time (rotate 5 degrees / second, x degrees per frame).
You can really lock Unity up using while loops improperly. The program waits for the loop to finish before taking the next step and an Infinte loop isn’t a good approach. (Python or Pygame maybe you’re used to? But this isn’t that good with C# API).
Edit:
Perhaps it isn’t such a bad idea to create a rotation speed?
private float rotationSpeed = 5f; // Set this however you wish
// Then in Rotate()
void Rotate()
{
tf.Rotate(new Vector3(0f, 0f, 6f * rotationSpeed * Time.deltaTime));
//Since you're updating frames within Update() use deltaTime
// to smooth the rotation cycles.
// If you use FixedUpdate() --- Preferred for calculations
// Use fixedDeltaTime instead.
}