Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • 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 /
  • Help Room /
avatar image
0
Question by a1steaksa · Jun 17, 2016 at 01:43 AM · componentactivateuse

How would I add a method to all gameobjects?

I'm sure a lot of this is not the correct way to do things, but I'm just getting started with C# and with Unity, so please bear with me on this one.

I'm trying to implement a simple "use" system so players can press E while looking at a gameobject and have it execute the "use" method stored on that gameobject. I have a very simple version of it working that turns a cube red when a player looks at it and presses E.

The issue I'm running into is that in order to even attempt to call the use() method I have in a script, added as a component to this cube, I have to guarantee to the compiler that the use() method exists, by first searching for the component containing the use() method via

gameObject.GetComponent<ColorChangeBlock>()

This would work fine if I wanted each and every usable item to act identically when used.

So I need to know how I can make this work. I think ideally I'd like to create a "useable" class with an empty default use function and have every gameobject extend that, but I'm not sure how I would go about doing that.

I'm very likely going about this all wrong, and I would love it if someone with more knowledge on the subject could help me out.

Comment
Add comment
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

2 Replies

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by phxvyper · Jun 17, 2016 at 02:47 AM

What you're looking for is probably Inheritance.

Have something along the lines of:

 public abstract class UsableItem : MonoBehaviour {
 
     // Abstract fields, properties and methods HAVE to be overriden by an inheriting type.
     public abstract void Use() {}
 }
 
 public class ColorChangingItem : UsableItem {
 
     public Renderer Renderer { get; private set; } 
 
     void Start() {
         Renderer = GetComponent<Renderer>();
     }
 
     // Override the abstract method
     public override void Use() {
         // Set color to black on player use.
         Renderer.material.SetColor(Color.black);
     }
 }
 
 public class MovingItem : UsableItem {
 
     // Override the abstract method
     public override void Use() {
         // Move this object up .5 units every time the player uses it.
         transform.Translate(new Vector3(0f, 0.5f, 0f));
     }
 }

And now you can attach MovingItem and ColorChangingItem to ANY GameObject, just like a normal Component/Script/MonoBehaviour. Then, when your player uses the item do:

 UsableItem item = usedItem.GetComponent<UsableItem>();
 if (item) item.Use();

And the method call will be dispatched accordingly to the overridden Use function, if any.

...Side Note... Instead, you could use SendMessage:

 usedItem.SendMessage("Use", SendMessageOptions.DontRequireReceiver);

However, this uses .NET Reflection, which is significantly slower than simply null-checking the component, like I did above.

Comment
Add comment · 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
0

Answer by a1steaksa · Jul 06, 2016 at 01:14 AM

Hey, @phxvyper thanks for the help.

Edit: Except never mind that's my bad I wasn't doing

 public class ColorChangeBlock : UsableItem {

Thanks again!

I'm just now back at trying to implement this and I'm getting an error with my color change and moving item code where it's telling me that

 `ColorChangeBlock.Use()' is marked as an override but no suitable method found to override

Any clue what would cause this?

The entire code for the color change block is

 public class ColorChangeBlock : MonoBehaviour {
     public override void Use() {
         gameObject.GetComponent<Renderer>().material.color = Color.red;
     }
 }

With my UsableItem code being

 public abstract class UsableItem : MonoBehaviour {
     public abstract void Use();
 }
Comment
Add comment · 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

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.

Follow this Question

Answers Answers and Comments

59 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

Related Questions

Activating Scripts in another Script? 2 Answers

Changing the order of Components 9 Answers

How to expose other components fields 0 Answers

New UI - Referencing deep nested components on an prefab instantiation 1 Answer

Depth of Field 1 Answer


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