How to make Usable component keep events in prefab
-
- Posts: 6
- Joined: Fri Sep 20, 2024 9:57 pm
How to make Usable component keep events in prefab
Is there a way to keep events in the usable component stored in the prefab? I often reference my player, but these events wont' save in the prefab. I understand that the references can be scene dependant, so can I create some sort of reference class or something and attach it to the object the usable is on, to hold reference to the player, or do I need to modify the Usable component somehow?
Re: How to make Usable component keep events in prefab
Hi,
If you need to do something on the player when a conversation starts, please see 07:00 of the Interaction Tutorial. You probably don't need to do anything on the Usable.
Otherwise, you'll need to create a script that connects references at runtime. Here's a hypothetical example:
If you need to do something on the player when a conversation starts, please see 07:00 of the Interaction Tutorial. You probably don't need to do anything on the Usable.
Otherwise, you'll need to create a script that connects references at runtime. Here's a hypothetical example:
Code: Select all
[RequireComponent(typeof(Usable))]
public class ConnectUsableEvents : MonoBehaviour
{
void Start()
{
var usable = GetComponent<Usable>();
usable.events.onUse.AddListener(PlayAudioOnUse);
}
void PlayAudioOnUse()
{
AudioManager.Instance.PlayUseSound();
}
}
-
- Posts: 6
- Joined: Fri Sep 20, 2024 9:57 pm
Re: How to make Usable component keep events in prefab
Example: A chest. I have a usable component attached to the chest, and I have a method on my player that I call from the OnUse, which rotates the player towards the chest and triggers and animation.
So in your example below, this is what I need to do?
So in your example below, this is what I need to do?
Re: How to make Usable component keep events in prefab
If you can make a global reference to your Player script (for example), something like:
(That's just example code. You won't want to exactly use transform.LookAt() like that since it will probably also tilt the player.)
Then you can do something like:
Code: Select all
public class Player : MonoBehaviour
{
public static Player Instance { get; set; }
void Awake()
{
Instance = this;
}
public void PlayInteractionAnimation(GameObject usableObject)
{
transform.LookAt(usableObject.transform);
GetComponent<Animator>().Play("interact");
}
...
Then you can do something like:
Code: Select all
[RequireComponent(typeof(Usable))]
public class UsableChest : MonoBehaviour
{
void Start()
{
var usable = GetComponent<Usable>();
usable.events.onUse.AddListener(MakePlayerInteract);
}
void MakePlayerInteract()
{
Player.Instance.PlayInteractionAnimation(this.gameObject);
}
}