Let’s say you have a simple PlayerComponent
, like this:
PlayerComponent.cs
using UnityEngine;
public class PlayerComponent : MonoBehaviour
{
public int health = 100;
}
You, for example, can create a different script that will reference instance of PlayerComponent
and change value of it’s health
field on Start
. This is the most basic way of referencing other components:
HurtPlayerOnStart.cs
using UnityEngine;
public class HurtPlayerOnStart : MonoBehaviour
{
[SerializeField] PlayerComponent _player;
void Start ()
{
if( _player!=null )
{
_player.health -= 10;
}
else Debug.LogWarning( "player component is null! Assign this field in the Inspector window" );
}
}
There are other ways of course. Like, you can use OnTriggerEnter
to look for PlayerComponent
components on colliders entering a trigger (special type of collider)
HurtZone.cs
using UnityEngine;
[RequireComponent(typeof(BoxCollider))]
public class HurtZone : MonoBehaviour
{
void Start ()
{
var collider = GetComponent<Collider>();
if( collider.isTrigger==false )
{
Debug.LogWarning( "this Collider must be a trigger for this script to work. Enable `Is Trigger` now!" , this );
}
}
void OnTriggerEnter ( Collider other )
{
var playerComp = other.GetComponent<PlayerComponent>();
if( playerComp!=null )
{
playerComp.health -= 10;
Debug.Log( "player damaged!" , this );
}
else Debug.Log( $"'{other.name}' has no {nameof(PlayerComponent)} so I will ignore it" , other );
}
}
→ Unity - Scripting API: Collider.OnTriggerEnter(Collider)
→ Unity - Manual: Introduction to collision
You can also “look” for colliders in specific direction and check for specific component instances with a Raycast operation.
HurtRay.cs
using UnityEngine;
public class HurtRay : MonoBehaviour
{
void FixedUpdate ()
{
const float rayLength = 10f;
Ray ray = new Ray( transform.position , transform.forward );
if( Physics.Raycast( ray , out RaycastHit hit , rayLength ) )
{
// hit
Debug.DrawLine( ray.origin , ray.origin + hit.point , Color.red , Time.fixedDeltaTime );
var playerComp = hit.collider.GetComponent<PlayerComponent>();
if( playerComp!=null )
{
playerComp.health -= 1;
Debug.Log( "player damaged!" , this );
}
else Debug.Log( $"'{hit.collider.name}' has no {nameof(PlayerComponent)} so I will ignore it" , hit.collider );
}
else
{
// miss
Debug.DrawLine( ray.origin , ray.origin + ray.direction * rayLength , Color.yellow , Time.fixedDeltaTime );
}
}
}
→ Unity - Scripting API: Physics.Raycast
Summary
This is how you can detect enemies or powerups - with triggers, collisions or raycasts basically.
Hope that helps and clears some confusion around this topic.