- Home /
Error trying to parse multiple IF statements of a KeyInput and Collider
I know that I am trying to parse a String and a Bool which isn't allowed but I'm unsure as to what the correct way is so I have done it this way so you can clearly see what I am trying to do.
I am trying to see if there is collision between object 'Boulder' and 'Player' and I am also checking to see if the player is pressing the key 'Space' so that I can execute a change of parent so that the boulder goes everywhere the player goes i.e Carrying the boulder.
I have little coding experience so an explanation of how to fix it and why it is done that way, would be really helpful so I can learn from my mistakes! Thanks
using UnityEngine;
using System.Collections;
public class BoulderController : MonoBehaviour {
public GameObject carrier;
// Update is called once per frame
void Update ()
{
//Used to stop the boulder going off the screen
if (transform.position.x <= -4.63f)
transform.position = new Vector3(-4.63f, transform.position.y, transform.position.z);
else if (transform.position.x >=7.03f)
transform.position = new Vector3(7.03f, transform.position.y, transform.position.z);
}
//Problem is caused by the below code
void OnTriggerEnter2D(Collider2D col)
{
if (col.gameObject.tag = "Player")
{
if (Input.GetKeyDown (KeyCode.Space))
{
col.gameObject.transform.parent = carrier.transform;
}
}
}
}
Line 22, you've used assignment ( =
) rather than equality checking ( ==
).
Also note that Gey$$anonymous$$eyDown
is only true for the first frame the key is pressed. You'd have to be quite lucky for that to be the same frame the trigger is entered. That's why Get$$anonymous$$ey
is better for this - it stays true while the key is held down.
Answer by Traces · Dec 09, 2015 at 09:06 AM
Ended up with this and it seems to work! - Might help someone else.
void OnTriggerEnter2D(Collider2D col)
{
if (col.gameObject.tag == "Boulder" )
{
if (Input.GetKey(KeyCode.Space))
{
col.gameObject.transform.position = transform.position;
col.gameObject.transform.parent = transform;
col.isTrigger = false;
col.enabled = false;
}
}
}