• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
Question by Khena_B · Oct 05, 2018 at 05:12 AM · inheritanceinterfaceeventsmethoddelegate

Interaction script

Hey,

I have an "Interactable" script that has the interaction logic, this script is used for all the interactable objects (chest, doors, NPC etc), the way I'm using it is by having it as a component, and using Action events that my other classes can subscribe to

 public event Action inRangeEvent;
 public event Action outOfRangeEvent;
 public event Action activateEvent;
 

My question is, is there a better, or simpler way to deal with a scenario like this, I'm still learning about Inheritance, Interfaces and Delegates, so far I've been using components over inheritance since it's more intuitive to me. What I do works fine, but I'm looking for some feedback.

**Edit:**Gave the Interface method a try and it seems to work well, and it seems simpler than having to subscribe and unsubscribe to events. Some feedback on this would be appreciated.

Comment

People who like this

0 Show 3
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image tormentoarmagedoom · Oct 05, 2018 at 09:48 AM 0
Share

Good day.

Its just a tip: If you need that every object in the scene react to the player distance, maybe you should combine a trigger collider with Distance() to detect the player. I mean, an object very far away from the player does not need to spend CPU each frame calculating distance.

As an example, you want the object to do something when player is closer than 50. Then make a collider of 75, and when the player enters the collider start calculating the distance. You will use less CPU than run Distacnce() in each Update of each object.

Bye!

avatar image Khena_B tormentoarmagedoom · Oct 05, 2018 at 02:14 PM 0
Share

Not every objects, just interactables, there aren't too many interactables in my game, I'm aware that I can use triggers but for this specific case I'm going with a distance check

avatar image DawidNorasDev · Oct 05, 2018 at 11:40 AM 0
Share

It's also good idea (just thought about it) to cache square of the desired distance you want the player to be in. Than, you can compare sqrMagnitude instead of magnitude / distance. You would spare calculating a root for every interactible you have. NOTE: Do not worry about this comment. It's optimization and do not do major optimization if it's not a problem. "Premature optimization is the ROOT of all evil (...)" ~Donald Knuth Pun intended

2 Replies

· Add your reply
  • Sort: 
avatar image
Best Answer

Answer by TreyH · Oct 05, 2018 at 03:51 PM

From the comments, this Interactable script is sitting on the same GameObject alongside other scripts you intend to interact with. If that's the case, then you can use interfaces to simplify things.

One nice part of interfaces is that you don't actually care what the object is, only what it's made of. In your case, you might consider making an interface with a bad name like IInteractable and requiring that your doors, keypads, light switches, etc all implement it:

 // Forgive the double II naming, you already had an Interactable
 // and the interface naming convention doesn't look great when the
 // interface's actual name starts with I also
 public interface IInteractable
 {
     // Require that anything implementing this interface have a function
     // that looks like this
     void Interact();
 }
 
 public class Door : MonoBehaviour, IInteractable
 {
     // Implement your interface, important that this is public as 
     // interfaces cannot require accessor keywords like public / private
     public void Interact()
     {
         Debug.Log("Door opened!");
     }
 }
 
 // Not sure what your class looks like
 public class Interactable : MonoBehaviour
 {
     // Cache whatever you should be interacting with
     private IInteractable interactableObject;
 
     void Awake()
     {   
         // GetComponent works with interfaces and other inheritance
         this.interactableObject = this.GetComponent<IInteractable>();
     }
 
     void Update()
     {   
         if (this.interactableObject != null && true /* some other condition */)
             this.interactableObject.Interact();
     }
 }
Comment

People who like this

0 Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Khena_B · Oct 05, 2018 at 03:54 PM 1
Share

Thanks, that's exactly what I've been doing after finding about interfaces and it seems simple enough, I just wanted some confirmation that this was the way to go for this particular case

avatar image

Answer by Bradybeast128 · Oct 05, 2018 at 02:32 PM

I don't know if I am understanding you question correctly, but you could just use Distance = Vector3.Distance(transform.position, player.GameObject.transform.position); if (distancefromplayer <= maxdistanceeventcanoccur) { //code for event here }

Comment

People who like this

0 Show 3 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Khena_B · Oct 05, 2018 at 02:37 PM 0
Share

That's not what I'm asking, I already have all the code in place, my question is, how can the Interactable script communicate with any other objects scripts (chest, NPC, door) on the same GameObject

avatar image TreyH Khena_B · Oct 05, 2018 at 03:00 PM 0
Share

Then your question isn't phrased properly. There are hundreds of other questions dealing with script interactions and almost as many ways to do it.

GetComponent
public fields for your components
private serialized fields
subscription (as you mention in your question)
collisions with triggers
a centralized manager
etc

If your other components are on the same GameObject, then it's even easier as you don't have to specify a specific transform when calling GetComponent.

 var door = GetComponent<Door>();
 
 // Whatever you want to do with the door


avatar image Khena_B TreyH · Oct 05, 2018 at 03:10 PM 0
Share

How can I use GetComponent when the Interactable script doesn't know which classes it interacts with, I know that I can use events, interfaces, what else, is there a simpler way? I don't see what's wrong with the question

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

99 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Need to inherit from EventArgs AND ScriptableObject 1 Answer

Question about events with arguments and ineritance 2 Answers

Can I use a delegate/event in Unity3D? 2 Answers

Use of Interfaces To Handle Two Object Types 2 Answers

How to choose base class to make Inherit C# 2 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges