충돌판정 오류
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerControl : MonoBehaviour
{
private Rigidbody rigidbody;
public float speed = 8f;
void Start()
{
rigidbody = GetComponent<Rigidbody>();
}
void Update()
{
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
float xspeed = x * speed;
float zspeed = z * speed;
Vector3 newvelo = new Vector3(xspeed, 0, zspeed);
rigidbody.velocity = newvelo;
}
public void Die()
{
gameObject.SetActive(false);
}
}
플레이어 컨트롤 스크립트
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletControl : MonoBehaviour
{
public float speed = 8f;
private Rigidbody rigidbody;
void Start()
{
this.rigidbody = GetComponent<Rigidbody>();
this.rigidbody.velocity = transform.forward * speed;
Destroy(gameObject, 3f);
}
// 추가
private void OnTriggerEnter(Collider other)
{
if(other.tag == "Player")
{
Debug.Log("충돌");
PlayerControl playerControl = GetComponent<PlayerControl>();
if(playerControl != null)
{
playerControl.Die();
}
}
}
}
총알 컨트롤 스크립트
여기서 충돌판정 파트만 보면
private void OnTriggerEnter(Collider other)
{
if(other.tag == "Player")
{
Debug.Log("충돌");
PlayerControl playerControl = GetComponent<PlayerControl>();
if(playerControl != null)
{
playerControl.Die();
}
}
}
1. 트리거로 충돌판정이 났을시 충돌한 오브젝트의 태그가 "Player"라면
2. PlayerControl 컴포넌트를 변수 playerControl에 불러온다
3. 변수 playerControl이 null값이 아니라면 PlayerControl에 있는 메서드 Die() 실행
public void Die()
{
gameObject.SetActive(false);
}
Die 메서드는 말 그대로 Player 오브젝트를 비활성화 시키는것이다
하지만 실행결과 충돌판정으로 Player 오브젝트가 사라지지 않는다
분명 "충돌"이 출력되는것을 보면 Player와 충돌판정까지는 되는것 같은데
Die() 메서드가 호출되지 않는것 같다
---------------------------------------------------------------------------------------------
private void OnTriggerEnter(Collider other)
{
if(other.tag == "Player")
{
Debug.Log("충돌");
PlayerControl playerControl = other.GetComponent<PlayerControl>();
if(playerControl != null)
{
playerControl.Die();
}
}
}
드디어 알아냈다. 컴포넌트를 불러오는 값에 other를 붙이지 않았었다
처음엔 컴포넌트를 불러오는건 다 똑같은게 아닌가라는 생각이 들었는데
other를 붙여야지만 other의 게임 오브젝트에 추가된 PlayerControl 타입의 컴포넌트를 변수에 할당할 수 있다