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 THaynes · Dec 29, 2016 at 06:41 AM · gameobjectscript.referenceoutside

How do I call a class' variable from a script on one object, from a script on another gameobject? The class/variables auto-complete in the code, but won't work in game.

I have a script on my player object called DynaControls that has variables that I want to be called from by enemies in my game. So I referenced the DynaControls script in a ESpawnLife script that is on my enemies. Everything seems to be connecting in code, but the variables are not being called in Unity. Nothing referencing 'DC' is working.

public class ESpawnLife : MonoBehaviour {

 public GameObject eMine;
 public GameObject eBullet;
 public GameObject player;

 public DynaControls DC;

 void Start ()
 {
     InvokeRepeating("SpawnMines", 2, 5);
        InvokeRepeating("SpawnBullets", 2, 10);

     DC = player.GetComponent<DynaControls>();
     //otherObject = GameObject.FindGameObjectWithTag("Player").GetComponent<GameObject>();
 }

 void Update ()
 {
     DC.dead = true;
     print("autodeath");

     if (DC.deleteAura == true)
     {
         print("seeing it");
     }
 }
 
 void SpawnMines()
 {
     Instantiate(eMine, this.transform.position, Quaternion.identity);
 }

 void SpawnBullets()
 {
     Instantiate(eBullet, this.transform.position, Quaternion.identity);
 }

 void OnCollisionEnter (Collision other)
 {
     if (other.gameObject.tag == "Player")
     {
         if (DC.deleteAura || DC.reterAura == true)
         {
             print("deathtouch");
             Destroy(this.gameObject);
         }
     }
 }

}

Comment
Add comment · Show 5
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 AlwaysSunny · Dec 29, 2016 at 06:41 AM 0
Share

When you say things like "isn't working" it's hard to know what you mean. You aren't getting a null ref exception when attempting to read or modify the DC variable? If not, that means the player.GetComponent line is working, and nothing visible here is obviously illegal. You'll have to elaborate a bit.

avatar image THaynes AlwaysSunny · Dec 29, 2016 at 11:58 AM 0
Share

Sorry, I couldn't really elaborate because I'm not getting any errors. At first I was getting null reference exceptions, before I added 'player' in front of GetComponent for my reference. And just to clarify: References to scripts and components from scripts that are attached to game objects that are children or parents of each other work fine. I'm just having issues with separate objects referencing each other.

avatar image AlwaysSunny THaynes · Dec 29, 2016 at 06:02 PM 0
Share

If you're still having trouble, you might need to show us the DynaControls script. Also make sure to always format pasted code with the 101010 button - should've scolded you about that to begin with! ;)

References don't care whether something is a parent/child, so that distinction is just a coincidence here.

Create a public void method on DynaControls called Debug$$anonymous$$e and try calling it immediately after getting the component from ESpawnLife. (just after line 11 as seen here). Also try modifying the GetComponent call as follows:

 DC = player.GetComponent<DynaControls>() as DynaControls;
 DC.Debug$$anonymous$$e();

In the DynaControls script...

 public void Debug$$anonymous$$e() { Debug.Log(" I was called successfully "); }

Is it possible the player variable is populated with the wrong object? Or maybe the player variable is referencing an object that accidentally has more than one instance of DynaControls as a component? $$anonymous$$aybe you're expecting a different instance of DynaControls to respond.

Show more comments

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by THaynes · Dec 29, 2016 at 08:21 PM

 using UnityEngine;
 using UnityEngine.UI;
 using System.Collections;
 using System;
 
 public class DynaControls : MonoBehaviour 
 {
     
     #region Singleton
     private static DynaControls _instance;
     public static DynaControls Instance;
     #endregion
 
     public delegate void OnMessageReceived();
 
     public delegate void SwitchEnemyHue(Color color);
     //public static event SwitchEnemyHue onEnemyHit;
 
     public float moveSpeed;
     public float rotSpeed;
     public Vector3 eularAngleVelocity;
     public bool reterAura = false;
     public bool deleteAura = false;
     public bool dead = false;
     public int areaEnemiesDead;
 
     public GameObject reterParticler;
     public GameObject deleteParticler;
 
     private Rigidbody rb;
 
     Slider[] HS;
     //Image CI;//game over canvas image
 
     void Start () 
     {
         rb = GetComponent <Rigidbody> ();
         HS = GetComponentsInChildren<Slider>();//0=Horo,1=Flak,2=Health
         //CI = GetComponentInChildren<Image>();
 
         dead = false;
     }
 
     public void DebugMe ()
     {
         Debug.Log("Called"); //this works fine. It's called as soon as the enemy spawns.
     }
 
     void OnCollisionEnter(Collision coll)
     {
         if (coll.gameObject.tag == "Enemy")
         {
             if (reterAura == false && deleteAura == false)
             {
                 HS[2].value--;
                 if (HS[2].value < 1)
                 {
                    // Destroy(this);
                    // dead = true;
                 }
             }
             if (reterAura == true)
             {
                 //Destroy(coll.gameObject);
 
                 HS[0].value++;
                 HS[1].value--;
             }
             if (deleteAura == true)
             {
                 //Destroy(coll.gameObject);
 
                 HS[0].value--;
                 HS[1].value++;
             }
         }
         if (coll.gameObject.tag == "Healer")
         {
             HS[2].value++;
             if (reterAura == true)
                 //Destroy(coll.gameObject);
                 HS[0].value++;
         }
     }
 
     void WriteMessage()
     {
 
     }
 
     void FixedUpdate () 
     {
         float x = (Input.GetAxis ("Horizontal") * moveSpeed * Time.fixedDeltaTime);
         float y = (Input.GetAxis ("Vertical") * moveSpeed * Time.fixedDeltaTime);
         float z = (Input.GetAxis ("HDepth") * moveSpeed * Time.fixedDeltaTime);
         rb.MovePosition (rb.position + (Vector3.right * x) + (Vector3.up * y) + (Vector3.forward * z));
 
         #region //Rotation (works, but is not being used)
         //        Quaternion deltaRotation = Quaternion.Euler (eularAngleVelocity * Time.deltaTime);
         //        float xR = (Input.GetAxis ("Shake") * rotSpeed * Time.fixedDeltaTime);
         //        float yR = (Input.GetAxis ("Nod") * rotSpeed * Time.fixedDeltaTime);
         //        float zR = (Input.GetAxis ("Tilt") * rotSpeed * Time.fixedDeltaTime);
         //        rb.MoveRotation (rb.rotation + (Quaternion.Euler * xR) + (Quaternion.Euler * yR) + (Quaternion.Angle * zR));
         //        transform.Rotate (new Vector3 (xR, yR, zR));
         #endregion
 
         if (Input.GetButtonDown("RETER"))
         {
             reterAura = true;
             reterParticler.SetActive(true);
         } else if (Input.GetButtonUp("RETER")){ reterAura = false; reterParticler.SetActive(false); }
 
         else if (Input.GetButtonDown("DELETE"))
         {
             deleteAura = true;
             deleteParticler.SetActive(true);
         }
         else if (Input.GetButtonUp("DELETE")) { deleteAura = false; deleteParticler.SetActive(false); }
     }
 
     //void Death ()
     //{
     //    if (dead == true)
     //    {
     //        CI.enabled = true;
     //    }
     //}
 }
Comment
Add comment · Show 5 · 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 AlwaysSunny · Dec 29, 2016 at 08:27 PM 0
Share

I assume the code referring to a singleton pattern is not being used, because I don't see it being written to.

Seeing this and your previous explanations is not enough information to explain what is happening. Please write a paragraph or two explaining exactly what you're doing with these scripts in your game. The behavior you report is not explained by seeing this code, so something else is going on that is not visible to me.

avatar image THaynes AlwaysSunny · Dec 29, 2016 at 11:07 PM 0
Share

Yes, the singleton is not being used.

So what is happening in my scene is that I have a player object that can enter an area with a box collider. When the area's collider is triggered, enemies (with the ESpawnLife script attached) spawn around the area and shoot bullets. These two scripts, DC and ESL, I'm trying to have interact when the gameobjects holding them touch to have various effects take place, such as losing heath, changing color, death, etc.

avatar image AlwaysSunny THaynes · Dec 29, 2016 at 11:30 PM 0
Share

Given what you said about changes taking place after playmode, it seems like you are operating on a prefab ins$$anonymous$$d of an instance of that prefab.

If you're assigning a prefab to the "player" variable (and no other code is acting on it which instantiates it) that is what's wrong. I assumed that you were assigning a GameObject instance which exists in the scene hierarchy to that variable.

I still can't deter$$anonymous$$e what the intended behavior is based on what I'm seeing, but I assume making changes to a prefab is unintentional, which means what you actually want the "player" variable to hold is a reference to a specific instance of whatever the "player" gameobject is.

Show more comments

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

Set object reference for script at runtime 0 Answers

Hi everyone.need help with this. 1 Answer

Access gameobject from a different scene... 1 Answer

One script for multiple enemy objects problem 2 Answers

Objects, GameObjects, Lists, and lists of GameObjects with Objects, oh my! 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