當我在YouTube上觀看關于無盡跑酷的第二部分的教程時,游戲物件在擊中玩家時不會消失
using System.Collections;
using System.Collections.Generic;
public class Obstacle : MonoBehaviour
{
public int damage = 1;
public float 速度。
private void Update()
{
transform.Translate(Vector2.left * speed * Time.deltaTime)。
}
void onTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("rocket"/span>))
{
//火箭的傷害為1。
other.GetComponent<rocket>().health -= damage;
Debug.Log(other.GetComponent<rocket>().health)。
Destroy(gameObject)。
}
}
}
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class rocket : MonoBehaviour
{
private Vector2 targetPos;
public float Yincrement;
public float 速度。
public float maxHeight;
public float minHeight;
public int health = 3;
void Update()
{
if (health <= 0)
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex)。
}
transform.position = Vector2.MoveTowards(transform.position, targetPos, speed * Time.deltaTime)。
if (Input.GetKeyDown(KeyCode.UpArrow) && transform.position.y < maxHeight)
{
targetPos = new Vector2(transform.position.x, transform.position.y Yincrement) 。
}
else if (Input.GetKeyDown(KeyCode.DownArrow) && transform.location.y > minHeight)
{
targetPos = new Vector2(transform.position.x, transform.position.y - Yincrement);
}
}
從這個https://www.youtube.com/watch?v=FVCW5189evI,我很困惑為什么它沒有作業,誰能告訴我哪里出了問題?
uj5u.com熱心網友回復:
如果你想摧毀使用這個,正確的方法是在碰撞時獲得游戲物件:other.gameObject
void onTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("rocket"/span>))
{
//火箭的傷害為1。
other.gameObject.GetComponent<rocket>().health -= damage;
Debug.Log(other.gameObject.GetComponent<rocket>().health)。
Destory(other.gameObject)。
}
}
uj5u.com熱心網友回復:
使用SetActive而不是Destroy函式。
void onTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("rocket"/span>))
{
//火箭的傷害為1。
other.gameObject.GetComponent<rocket>().health -= damage;
Debug.Log(other.gameObject.GetComponent<rocket>().health)。
gameObject.SetActive(false);//它將隱藏GameObject而不是銷毀。
// gameObject.SetActive(true);// 再次顯示。
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/312679.html
標籤:
