• 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
0
Question by Bamboy · Sep 15, 2012 at 04:31 AM · c#variablemethod

Issues with C# script interactions

I have been struggling with using methods and variables across different scripts for a while, and have done quite a bit of googling about the various ways it can be done. I have even restarted from scratch a few times.

Is there a certain location relationship you need for these things? Like is there a difference between getting variables and methods from a script on the same object versus in the same parent tree or just in the scene? (And from other scenes, if that is possible)

This code doesn't involve it, but does declaring static or public, exc variables/methods matter when trying to get them from other codes? I have had Unity give me errors about something being static when I didn't have anything static in the whole scene.

Error:

NullReferenceException: Object reference not set to an instance of an object PlayerActions.Update () (at Assets/Content/Scripts/PlayerActions.cs:51)

My Code:

 using UnityEngine;
 using System.Collections;
 
 public class PlayerActions : MonoBehaviour {
     
     OTAnimatingSprite sprite;
     
     // Declares User Input Keys
     bool input_moveLeft;
     bool input_moveRight;
     bool input_jump;
     
     // Use this for initialization
     void Start () {
         sprite = OT.ObjectByName("PlayerAnimations") as OTAnimatingSprite;
         sprite.InitCallBacks(this);
         
         sprite.PlayLoop("idle");
     }
     
     // Update is called once per frame
     void Update () {
         // -------------KEY BINDINGS-------------------
         if ( Input.GetKey("space") )                      // Jump
             input_jump = true;
         else
             input_jump = false;
         
         if ( Input.GetKey("a") || Input.GetKey("left") )  // Move Left
             input_moveLeft = true;
         else
             input_moveLeft = false;
         
         if ( Input.GetKey("d") || Input.GetKey("right") ) // Move Right
             input_moveRight = true;
         else
             input_moveRight = false;
         // -------------KEY BINDINGS-------------------
         
         if ( input_moveLeft ) // -X
         {
                     sprite.PlayLoop("move");
         }
         else if ( input_moveRight ) // +X
         {
                     sprite.PlayLoopBackward("move");
         }
         else
         {
             sprite.PlayLoop("idle");
         }
 
     }
 }

Code I am trying to follow: http://www.wyrmtale.com/orthello/animations (Scroll down to 'C# Source Code')

P.S. It really confuses me for the examples that name things such as GameObject as they don't directly say what I should be filling in with my own variables, or even what my variables should be. (I mean they do, but in a confusing way.)

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

1 Reply

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

Answer by hdgam3r · Sep 15, 2012 at 07:02 AM

It´s very simple actually.

If you want to get a variable from a script (Component) on the same object hierarchy, you only have to reference the gameObject component and then make a search for the script:

 gameObject.GetComponent<YourScriptName>().yourPublicVariable;

Notice the lowercase g, this means that we are searching for the component on our current game object.

You can´t reference other scenes objects. If you want to find for a script attached to another GameObject, you have to use the GameObject class and find (via name, tag, etc.)

 GameObject.Find("ObjectName").GetComponent<YourScriptName>().yourPublicVariable;

Note that now we are using a G.

Comment
Add comment · 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 fafase · Sep 15, 2012 at 07:34 AM 0
Share

Note also that if this is done regularly, it is to be avoided. You 'd rather create a reference to the object:

  ScriptName reference;

  void Start(){
     reference = GameObject.Find("Object").GetComponent<ScriptName>();
  }
  void Update(){
     reference.theVariable += 10;
  }

The problem is that Find() needs to find the object among all of your hierarchy, if you have two objects, no worries, if you have thousands, your game will freeze until the object is found. The freeze can be unnoticed or 1/2second or even more.

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

11 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

Related Questions

Multiple Cars not working 1 Answer

Storing a method in a variable 2 Answers

Distribute terrain in zones 3 Answers

Why the variable don't change your value? 1 Answer

Why do I get this error: "Assets/Scripts/Parkour Movement.cs(15,38): error CS0119: Expression denotes a `type', where a `variable', `value' or `method group' was expected" 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