Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 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 /
avatar image
0
Question by lavapig · Jan 26, 2015 at 07:48 AM · c#gameobjectgetcomponent

how to change gameobject variable to a different gameobject in c#

Hi guys! I thought that this would be relatively simple but I have spent hours trying to figure out how I can change a GameObject variable to another GameObject in C#.

Here is my current code :

 using UnityEngine;
 using System.Collections;
 
 public class infect : MonoBehaviour {
 
     public GameObject replicationClass;
 
     void OnCollisionEnter(Collision collision) {
         if (collision.transform.GetComponent<stats> ().status == 1) {
                         collision.transform.GetComponent<stats> ().status = 2;
 
                         collision.transform.GetComponent<replicate> ().replication =  replicationClass;
                         Destroy (gameObject, (Time.deltaTime * 20));
                 }
         }
 
 }
 

I am trying to change the replication GameObject of the replication script, to the replicationClass GameObject variable defined on line 6. However all this does is set replication (in the replication script) to null and gives me the

MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object.

error when I run the program. I am very confused as to why this does not work.

Below is my replication script :

 using UnityEngine;
 using System.Collections;
 
 public class replicate : MonoBehaviour {
 
     public float timeLeft = 30.0f;
     public float requiredTime = 30.0f;
     public GameObject replication;
     public GameObject WorldScript;
 
     void Awake(){
         timeLeft = requiredTime;
     }
 
     void Update()
     {
         timeLeft -= Time.deltaTime;
         if(timeLeft < 0)
         {
             timeLeft = requiredTime;
             Debug.Log (replication);
             if(WorldScript.GetComponent<worldStats>().currentCells < WorldScript.GetComponent<worldStats>().maxCells)
             Instantiate(replication, gameObject.transform.FindChild("spawnPoint").position, transform.rotation);
 
         }
     }
 }

Does anybody know what I'm doing wrong here? Thank you very much for your time and help =) I would appreciate it if all code you showed me was in C#

Comment
Add comment · 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 moonstruck · Jan 26, 2015 at 09:11 AM 0
Share

Hello, need some information to answer your question, what is replicationClass object? Is it a prefab or a scene object. You may get this exception if this object is a child of infect game object that gets destroyed. From the first glance you have issues with hierarchy.

avatar image sniper43 · Jan 26, 2015 at 11:37 AM 0
Share

http://unity3d.com/learn/tutorials/modules/beginner/live-training-archive/object-pooling

Try to adapt your script to use object pooling ins$$anonymous$$d. Assu$$anonymous$$g you have a lot of gameobjects, it will QUIC$$anonymous$$LY become too processor heavy to destroy/instantiate new objects.

Anyway: why are you destroying infect? Please provide info on this.

avatar image lavapig · Jan 29, 2015 at 05:15 PM 0
Share

Sorry for the confusion guys. replicationClass is a gameObject (its itself, actually).

2 Replies

· Add your reply
  • Sort: 
avatar image
0

Answer by karma0413 · Jan 29, 2015 at 09:49 PM

I am a newbie. But I have had some problem between understanding TYPES.

An easy way for me to get the right one is 2 ways:

  1. Understanding types... While you defined replicationClass correctly, isn't it technically a wrong name...... maybe you should call it replicationObject, because after all this variable you defined as a GameObject. Now, if you have this (infect) script attached to some gameobject on the scene... Then you simply define it different..... lets call it replicationObject instead please.. and use this code in it's place...

      //Defining a parameter
         int a = replicationObject.GetComponent <Infect> ().somevariablethatisinsidetheinfectscript;
         
         //Calling a method
         bool didHeInfectSomeone = replicationObject.GetComponent <Infect> ().IInfectedSomeone ();
         
         
         //and then inside the infect, you can set a method after update that says something like:
         public bool IInfectedSomeone ()
         {
           return myInfectionStatus; // we may have set this to false initially, or whatever.. hopefully you see what I am doing with the script
         }
     
    
    
    

So hopefully as you can see. When we want to access the Class, we simply access it as part of a component of the actual gameobject in the scene. Because that's all scripts really are.

I am not the best about STATIC scripts. but if you research how to make a Class script STATIC... Then you can access it a little easier. and intead use phrasing like:

 int a = Infect.somevariableIhaveinsideThisScript;
 
 if (Infect.IInfectedSomeone)
 {
  print ("Holy cow, he infected someone");
 }



the 2nd way

to access understanding it... Is using the drag and drop method in the Unity Editor.

As you have your code currently setup... All you have to do is attach the Infect script to "some game object inside the scene". And then inside the UnityEditor for drag in the Object that you added the infect script to.... It's that simple.

But again, when calling it... You will still have to call it as a GetComponent of that object.

For collisions, they are obviously another component of the Gameobject...

 collision.GameObject.GetComponent <Infect> ().variable = 2;
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 moonstruck · Jan 30, 2015 at 08:46 PM

If replicationClass is the object itself than the problem is obvious: you assign the reference to this object to another script and destroy the object then try to Instantiate from that destroyed object. Try changing replicationClass to a prefab reference (probably created from the same object) and it will work.

P.S. You have a lot of GetComponent's in your code, they make the code less readable and most likely less efficient, try using variables to store these references like:

void OnCollisionEnter(Collision collision) {
    stats s = collision.transform.GetComponent();
    if (s.status == 1) {
        s.status = 2;
        collision.transform.GetComponent ().replication = replicationClass;
        Destroy (gameObject, (Time.deltaTime * 20));
    }
}

Also it would be cool changing WorldScript variable type to worldStats since you don't use operation on the object itself, only that script.

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

5 People are following this question.

avatar image avatar image avatar image avatar image avatar image

Related Questions

How to run a function in a GO that have DontDestroyOnLoad 1 Answer

C# GetComponent / change values throught other script 3 Answers

Null Reference Exception Help 1 Answer

Multiple Cars not working 1 Answer

GetComponent error 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