Setting Usable OnUse event method through script

Announcements, support questions, and discussion for the Dialogue System.
Post Reply
User avatar
pixelglitch
Posts: 6
Joined: Sun Sep 16, 2018 10:26 pm
Location: Denver, CO
Contact:

Setting Usable OnUse event method through script

Post by pixelglitch »

Hey there Toni,
I've been running into a slight issue regarding the Usable scripts OnUse event with prefabs and was wondering if you'd be able to help?

Right now I'm using the OnUse event to call a method with a passed gameobject that allows the player to hold the item.

onuse-proper.png
onuse-proper.png (17.81 KiB) Viewed 167 times

That gameobject works fine on its own, but whenever I instantiate a prefab of it into a scene it'll load without the reference to the player method and grabbed gameobject since it has no reference of the player in the main scene.

onuse-empty.png
onuse-empty.png (12.43 KiB) Viewed 167 times

I attempted to find a way to set the OnUse method and gameobject on the prefabs Start() method, but haven't been able to get it to work.

Any ideas?

Thanks!
User avatar
Tony Li
Posts: 22049
Joined: Thu Jul 18, 2013 1:27 pm

Re: Setting Usable OnUse event method through script

Post by Tony Li »

Hi,

There are two ways you can handle it:

1. Add a script to the Usable prefab that has a method that finds the player at runtime. In the inspector, assign this method to the OnUse() event. Example:

Code: Select all

public void TogglePickupOnPlayer(GameObject item)
{
    var objectDragBehaviour = GameObject.FindWithTag("Player").GetComponent<ObjectDragBehaviour>();
    objectDragBehaviour.TogglePickup(item);
}
2. Or leave the OnUse() event unassigned, and assign it at runtime. Example:

Code: Select all

GetComponent<Usable>().events.OnUse.AddListener(() =>
{
    var objectDragBehaviour = GameObject.FindWithTag("Player").GetComponent<ObjectDragBehaviour>();
    objectDragBehaviour.TogglePickup(item);
});
User avatar
pixelglitch
Posts: 6
Joined: Sun Sep 16, 2018 10:26 pm
Location: Denver, CO
Contact:

Re: Setting Usable OnUse event method through script

Post by pixelglitch »

You're the man Tony, appreciate the fast help and solid code samples. 👍
User avatar
Tony Li
Posts: 22049
Joined: Thu Jul 18, 2013 1:27 pm

Re: Setting Usable OnUse event method through script

Post by Tony Li »

Happy to help!
Post Reply