Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
12 Jun 22 - 14 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 FarmerJoe · Apr 12, 2016 at 07:24 PM · c#getcomponentreference

How to pull a variable from a separate C# script.

I am trying to pull a variable from another script within Unity using C#. I am building a game in which I need to reference a specific script depending on the location of objects in the scene. This variable has a constant value but this value will change from script to script. However, there seems to be an error with our code below, it will not recognize any of our GetComponet statements and we cannot pull any variables from that script into the main script. I can be more specific if the information provided is insufficient. Thank you!

 using UnityEngine;
 using System.Collections;
 
 public class Base : MonoBehaviour {
     string team = "neutral";
     public bool cpt = true;
 
     void Start () {
     
     }
     
     void Update () {
     
     }
 }
 

The variable pulled from this script will be the Boolean cpt and will be referenced here:

 using UnityEngine;
 using System.Collections;
 
 public class EntityMove : MonoBehaviour {
 
     private Vector3 cursorPosition;
     private Vector3 entityPosition; 
     private bool cpt = false;
 
     void Start () {
 
         GameObject.Find("cursor").GetComponent<menuAll> ().enabled = false;
     }
 
     void Update () {
         cursorPosition = GameObject.Find("cursor").transform.position;
         entityPosition = transform.position;
 
         float dist = Vector3.Distance (entityPosition, cursorPosition);
         if ((dist == 0) && Input.GetButtonDown ("Select") ) {
             print ("It works");
 
 //reference cpt in the following conditional statement
 
             if (cpt == true) {
                 GameObject.Find ("cursor").GetComponent<menuAll> ().enabled = true;
                 GameObject.Find ("cursor").GetComponent<CursorMove> ().enabled = false;
             }
         }
     }
 }
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
1
Best Answer

Answer by M-Hanssen · Apr 12, 2016 at 07:51 PM

First of all, you should really educate yourself into writing proper c# code.

To use variables (Fields) from other components (MonoBehaviour), your variables should be marked internal or public (this is correct in your case). However you should understand the concept when using other object's variables, you should have access to the object of where the variable is coming from.

In your example (if I'm correct) you would like to use the "cpt" variable from the "Base" class inside your "EntityMove" class. In order to achieve this your code should look as follow (I corrected some C# ugliness if you don't mind):

 public class Base : MonoBehaviour
     { 
         public bool Cpt = true;
         private string team = "neutral";
 
         protected void Start()
         {
 
         }
 
         protected void Update()
         {
 
         }
     }
 
     public class EntityMove : MonoBehaviour
     {
         private Vector3 cursorPosition;
         private Vector3 entityPosition;
         private Base baseClass;
         private GameObject cursor;
         private menuAll menuAll; // Please start public classnames with a Capital letter! (menuAll => MenuAll)
         private CursorMove cursorMove;
 
         protected void Start()
         {
             baseClass = FindObjectOfType<Base>();
             // Please don't use string based find queries but try to use FindObjectOfType<T>() of even better GetComponent<T>()
             // This is safer and faster
             cursor = GameObject.Find("cursor");
             menuAll = cursor.GetComponent<menuAll>();
             cursorMove = cursor.GetComponent<CursorMove>();
             menuAll.enabled = false;
         }
 
         protected void Update()
         {
             cursorPosition = cursor.transform.position;
             entityPosition = transform.position;
 
             float dist = Vector3.Distance(entityPosition, cursorPosition);
             if ((dist == 0) && Input.GetButtonDown("Select"))
             {
                 print("It works");
 
                 if (baseClass.Cpt)
                 {
                     menuAll.enabled = true;
                     cursorMove.enabled = false;
                 }
             }
         }
     }

However what I think that you actually want to do is to let the class "EntityMove" inherit from "Base". This requires a bit more C# knowledge about inheritance, but should look like this:

 public class Base : MonoBehaviour
     { 
         protected bool Cpt = true;
         protected string team = "neutral";
 
         protected void Start()
         {
 
         }
 
         protected void Update()
         {
 
         }
     }
 
     public class EntityMove : Base
     {
         private Vector3 cursorPosition;
         private Vector3 entityPosition;
         private GameObject cursor;
         private menuAll menuAll; // Please start public classnames with a Capital letter! (menuAll => MenuAll)
         private CursorMove cursorMove;
 
         protected void Start()
         {
             // Please don't use string based find queries but try to use FindObjectOfType<T>() of even better GetComponent<T>()
             // This is safer and faster
             cursor = GameObject.Find("cursor");
             menuAll = cursor.GetComponent<menuAll>();
             cursorMove = cursor.GetComponent<CursorMove>();
             menuAll.enabled = false;
         }
 
         protected void Update()
         {
             cursorPosition = cursor.transform.position;
             entityPosition = transform.position;
 
             float dist = Vector3.Distance(entityPosition, cursorPosition);
             if ((dist == 0) && Input.GetButtonDown("Select"))
             {
                 print("It works");
 
                 if (Cpt)
                 {
                     menuAll.enabled = true;
                     cursorMove.enabled = false;
                 }
             }
         }
     }

Good luck on your coding adventure and try to do some C# tutorials to learn more in depth C# and .NET knowledge.

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 FarmerJoe · Apr 13, 2016 at 07:40 PM 0
Share

Thank you so much for your help, I am a high school student and am still trying to grasp the concepts involved with Unity and C#. The code you gave me with class inheritance worked perfectly and I am now starting to understand these concepts. Thank you for your patience and I do now see the problems with my previous code.

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

5 People are following this question.

avatar image avatar image avatar image avatar image avatar image

Related Questions

Pass a value between script or else by reference? 1 Answer

Instatiated object not being referenced in Start function? 2 Answers

Getting Int value from script to other script 2 Answers

Moving code from external c# project library into Unity without loosing references 0 Answers

Not sure how to make my classes interact in the way I intend them to 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