I want Unity to erase objects with collision determination script

Asked 2 years ago, Updated 2 years ago, 59 views

I was making a game like billiards in Unity and I wanted to make sure that the Sphere disappeared when it hit the hole (Cylinder), but the script I wrote didn't respond to any errors.I would appreciate it if you could point out the improvements.

using System.Collections;
using System.Collections.General;
using UnityEngine;

public class myscript:MonoBehavior {

    // Use this for initialization
    void Start() {

    }

    // Update is called once per frame
    void Update() {
        GameObjectsphere=GameObject.Find("Sphere");
        Rigidbody rigidbody=GetComponent<Rigidbody>();    
    }

    private void OnCollisionEnter(Collision){
        if(collision.gameObject.tag=="Player"){
            collision.gameObject.SetActive(false);
        }
    }
}

This is what it looks like

c# unity3d

2022-09-30 18:25

1 Answers

Let's talk about the following assumptions.

Sphere: Move with Player tag and Rigidbody component
with myscript script Cylinder: Rigidbody Component not attached and will not move

The OnCollisionEnter method returns an object whose object has Rigidbody crashed as the Collision class of the argument.
In other words, when a ball hits a hole, the value of collision is filled with holes.

If you run 1. with the code below, the hole will disappear if the hole has a Player tag.
If you have myscript attached to Sphere, you can retrieve and erase Sphere itself in this.
Rewrite the code below to 2. to see if it works for you.

private void OnCollisionEnter (Collision collision)
{
    // 1. Player disappears when the tag of the moving object is Player
    if(collision.gameObject.tag=="Player")
    {
        collision.gameObject.SetActive(false);
    }
    // 2. When the tag of the moving object is Player, the player itself disappears.
    if(this.gameObject.tag=="Player")
    {
        This.gameObject.SetActive(false);
    }
}

If IsTrigger is checked for either object, OnTriggerEnter occurs instead of OnCollisionEnter.
If the above code does not work, please check the following:

Confirmation


2022-09-30 18:25

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.