0
\$\begingroup\$

I'm trying to make a simple game where you move a sphere from left/right and try to avoid falling cubes. If a cube touches the player (sphere), the player dies. I'm trying to set up boundaries using a cylinder with a collider, but every time I hit the collider boundary, the player disappears like they would if they hit a cube. Here is my player script:

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;

public class Move : MonoBehaviour
{
public float moveSpeed = 1;

// Start is called before the first frame update
void Start()
{

}

// Update is called once per frame
void Update()
{

    transform.position += new Vector3(Input.GetAxis("Horizontal") * moveSpeed, 0, 0);
}

void OnCollisionEnter(Collision collision)
{
    if (collision.gameObject.tag == "Cube")
    {
        Destroy(collision.gameObject);
        Destroy(gameObject);
    }
}

}

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

To make the if condition apply to both lines, put braces around them like this:

void OnCollisionEnter(Collision collision)
{
    if (collision.gameObject.tag == "Cube")
    {
        Destroy(collision.gameObject);
        Destroy(gameObject);
    }
}

Note: get in the habit of always using braces with if-, while-, and for-statements to make it explicitly clear what lines the statement applies to.

\$\endgroup\$
7
  • \$\begingroup\$ I put in the code and the boundary works, but now the player doesn't disappear when the cube hits it \$\endgroup\$
    – a_z22
    Mar 27, 2020 at 15:21
  • \$\begingroup\$ Does the cube still disappear? And please show your updated code. \$\endgroup\$
    – Sirius 5
    Mar 27, 2020 at 16:20
  • \$\begingroup\$ No, I need the sphere to disappear, not the cubes. \$\endgroup\$
    – a_z22
    Mar 27, 2020 at 16:48
  • \$\begingroup\$ I assumed that collison.gameObject refers to the Cube object, and gameObject refers to the player object (i.e. this script is on the player). Is that correct? Is the problem that Destroy(gameObject) is not destroying the player/sphere? But can you confirm that Destroy(collision.gameObject) is still destroying the Cube? \$\endgroup\$
    – Sirius 5
    Mar 27, 2020 at 17:13
  • \$\begingroup\$ The cubes aren't supposed to get destroyed, the only thing I want to get destroyed is the player, which is the sphere \$\endgroup\$
    – a_z22
    Mar 27, 2020 at 18:13

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .