Home > OS >  Trying to destroy one gameobject in unity
Trying to destroy one gameobject in unity

Time:03-15

I am trying to destroy one gameobject in unity, not all of them and not all of them with Input.touchCount. How do I do that?

Ray ray;
RaycastHit hit;

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

// Update is called once per frame
void Update()
{
    if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
        ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);

    if (Physics.Raycast(ray, out hit, Mathf.Infinity)) 
    {
        Debug.Log("hit something");
        Destroy(hit.transform.gameObject);
    }
    else
    {
        if (Input.touchCount > 0)
        {
            Vector2 touchDeltaPosition = Input.GetTouch(0).deltaPosition;
        }
    }
}

CodePudding user response:

I'm pretty sure you would like your first if check wrap the entire thing, not only the first line.

Currently you are every frame firing a Raycast and destroy whatever you hit.

You rather want to only do this once per tap like e.g.

void Update()
{
    if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
    {
        var ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);

        if (Physics.Raycast(ray, out var hit)) 
        {
            Debug.Log("hit something");
            Destroy(hit.transform.gameObject);
        }
    }
}

CodePudding user response:

It's obvious that your if statement is missing a bracket {}, If your "Destory()" method can't ecstasy a game object, try the "DestroyImmediate()" method. DestroyImmediate will be destroyed as soon as it is destroyed, and the memory will be released. It takes more time to perform this operation and affects the main thread, while Destroy is destroyed asynchronously, which is generally destroyed in the next frame and will not affect the main thread. enter image description here

  • Related