using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float JumpForceMagnitude = 10000f;
Vector3 JumpForce;
float MaxHeight = 20.97323f; // This is the height that the player jumps
//float max = 0;
Collider2D col;
Rigidbody2D rb;
void Start()
{
JumpForce = new Vector3(0, JumpForceMagnitude, 0);
rb = GetComponent<Rigidbody2D>();
col = GetComponent<Collider2D>();
}
void Update()
{
if (rb.velocity.y > 0)
{
if(col.enabled == true)
col.enabled = false;
}
else
{
if (col.enabled == false)
col.enabled = true;
}
//if (max < transform.position.y)
// max = transform.position.y;
//Debug.Log(max);
if (Input.GetKeyDown(KeyCode.Space))
{
if (transform.parent != null) // If player is on platform, jump up
{
rb.AddForce(JumpForce, ForceMode2D.Impulse);
}
else
rb.AddForce(-JumpForce, ForceMode2D.Impulse);
}
}
private void OnCollisionStay2D(Collision2D collision)
{
if (collision.gameObject.tag == "Platform")
{
transform.parent = collision.transform;
}
}
private void OnCollisionExit2D(Collision2D collision)
{
transform.parent = null;
}
}
I am calling GetComponent exactly once.
As you said, setting collider to false and true immediately doesnt make sense, yeah but it should work right. I am getting the Runtime Errors (not compilation errors) as :
I don’t know about your error messages; I cannot get them to reproduce.
The thing is that the following code makes the collider be enable and disabled once per frame, one frame the collider is enabled, the following frame it’s disabled and so on (which could explain your error messages):
But your script is setting the collider to on if it’s off. I want it to toggle when it goes up vs comes down. I think my code is fine and the instantaneous toggle isn’t causing the runtime error. There is something else about this.
I got it working by keeping the exact same code but changing col.enabled = true and false to isTrigger = false and true. So instantaneous toggle isn’t really a problem, else this code would also have given unexpected results.