I’m making a platformer in Unity, and in making the first boss battle I have a bug with the blocks that fall when you land on them, then stop falling then get moved back up to their starting position. The bug is that they fall, and Reset fine, but they just fall back down
here is the code:
using System.Collections;
using UnityEngine;
public class PlatformFall : MonoBehaviour
{
[Header("Basic variables")]
[Tooltip("How long to delay before dropping the platform")]
public float fallDelay = 0.3f; // The delay before the platform falls
public bool isFalling = false;
[Header("Boss fighting variables")]
public float waitToReanstantiate = 1f;
//public Transform respawnPoint;
public Vector2 startingPos;
private BoxCollider2D boxCollider;
private new Rigidbody2D rigidbody; // The rigidbody
void Awake()
{
// Finding components
rigidbody = GetComponent<Rigidbody2D>();
boxCollider = GetComponent<BoxCollider2D>();
}
void Start()
{
// Set the respawing point
startingPos = transform.position;
}
// Whenever a collision hits the platform run this method
void OnCollisionEnter2D(Collision2D other)
{
// If the gameObject has the Player tag, then run this
if (other.gameObject.CompareTag("Player"))
{
Invoke("Fall", fallDelay); // Drop the platform after fallDelay, defined on line 6, times out
}
}
// This gets invoked to drop the platforms
void Fall()
{
rigidbody.isKinematic = false; // Use the physics engine
boxCollider.isTrigger = true; // Make the collider a trigger, so it can't collide with anything else
isFalling = true; // Make the block fall
}
void Respawn ()
{
StartCoroutine("RespawnCo");
}
IEnumerator RespawnCo()
{
yield return new WaitForSeconds(waitToReanstantiate); // Wait for a while
isFalling = false; // Stop it from falling
rigidbody.isKinematic = true;
boxCollider.isTrigger = false;
transform.position = startingPos; // Reset the position
}
private void OnTriggerEnter2D(Collider2D other)
{
// If the block collides with the killzone, then turn off the gameobject and reset weather it can fall
if(other.tag == "Killzone")
{
rigidbody.isKinematic = true;
boxCollider.isTrigger = false;
isFalling = false;
Respawn();
}
}
}