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
1
Question by safak93 · Apr 18, 2014 at 09:15 PM · instantiateprefabassign

How to assign GameObject to a instantiated prefab via Script(C#)?

I have a enemy-prefab with a EnemyHealthController. In the EnemyHealhController there is a public Script-Variables for two different GameObjects. Now when I instantiate a new enemy-prefab to the current scene, the variables are unassigned. I would that the variable should assigned to the Player in the current scene without drag and drop or select. Is there a solution to solve this problem?

From this:

alt text

to this:

alt text

The public Scripts-Variables are:

 public EnemyCount enemycount;
 public ExpSystem expSystem;



EnemyHealthController:

 using UnityEngine;
     using System.Collections;
      
     public class EnemyHealthController : MonoBehaviour {
      
             public float currentHealth = 2;
             public float DamageEffectPause = 0.2F;
 
             public ExpSystem expSystem;
             public EnemyCount enemycount;
      
             void ApplyDamage(float damage)
             {
                    
                     if (currentHealth > 0)
                     {
                            
                             currentHealth -= damage;
                            
                             if (currentHealth <= 0)
                             {
                                     currentHealth = 0;                     
                                     Die();
                             }      
                             else
                             {
                                     StartCoroutine(DamageEffect());
                             }
                     }
             }
      
             IEnumerator DamageEffect()
             {
                     renderer.enabled = false;
                     yield return new WaitForSeconds(DamageEffectPause);
                     renderer.enabled = true;
                     yield return new WaitForSeconds(DamageEffectPause);
                     renderer.enabled = false;
                     yield return new WaitForSeconds(DamageEffectPause);
                     renderer.enabled = true;
                     yield return new WaitForSeconds(DamageEffectPause);
                     renderer.enabled = true;
             }
      
             void Die()
             {
                     expSystem.curEXP += 10;
                     enemycount.enemyCount--;
                     Destroy (gameObject);
             }
     }

unbenannt.png (10.9 kB)
unbenannt4.png (65.7 kB)
Comment
Add comment · Show 2
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 makled · Dec 20, 2017 at 02:28 PM 0
Share

Hey Guys, Is there a better way other than using find? as find goes through the entire gameobjects in the scene and is a computationally expensive?

avatar image nikimiaus makled · Nov 30, 2019 at 06:46 PM 0
Share

Exactly.

Currently giving a result proyect using find() results in an F because of computational drag. $$anonymous$$y $$anonymous$$cher won't always answer me how to solve troubles and this problem is goiing to be very recurrent I bet.

Glad to know I stumbled into something interesting tho.

2 Replies

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

Answer by Minchuilla · Apr 19, 2014 at 03:53 PM

Firstly, you say that your public script variables are GameObject but you your code defines them as the type of EnemyCount, which I don't think is a type unless you have a class named after it.

So what you need to do is this:

-change you variables to this

 public GameObject enemycount;
 public GameObject expSystem;

-to get the GameObject in code do as you have done in the comments

 newEnemy.GetComponent<EnemyHealthController>().enemycount = GameObject.Find("name of GameObject");

-if you still get an error with this line then you might have to cast it although I don't think that would make a difference as GameObject.Find returns a GameObject

i.e.

 newEnemy.GetComponent<EnemyHealthController>().enemycount = (GameObject)GameObject.Find("EnemySpawn");

Hope you problem is solved and feel free ask more questions

Minchuilla

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 safak93 · Apr 19, 2014 at 07:22 PM 0
Share

Thanks man you helped me. The enemy-prefab has a children with a component. I have tried it with:

 spawnObject.GetComponentInChildren<stomp> ().controller = GameObject.Find ("Player");

but they don't assign it. How should I do that?

Is there a alternative to GameObject.Find(), because I have heard that it's slow.

avatar image Minchuilla · Apr 19, 2014 at 07:42 PM 0
Share

Sorry, could you just clarify what you are trying to do and what isn't working.

Your code should work as long as your variable "controller" is of the type GameObject.

As far as I know GameObject.Find isn't slow and shouldn't prevent your program from working.

$$anonymous$$inchuilla

avatar image safak93 · Apr 19, 2014 at 11:07 PM 0
Share

I instantiate a enemy-prefab. Now the enemy has a child. The child(squishybox) has a script-component. I try to assign to the child-script a gameobject with GetComponentInChildren<>() but they don't assign them.

alt text

unbenannt-2.jpg (91.9 kB)
avatar image Minchuilla · Apr 20, 2014 at 10:00 AM 0
Share

I recommend that you have a look at the docs below:

GameObject.Find:

http://docs.unity3d.com/Documentation/ScriptReference/GameObject.Find.html

How to assign things:

http://docs.unity3d.com/412/Documentation/ScriptReference/index.Accessing_Other_Game_Objects.html

You could also try this to get the variable but this isn't recommended:

 spawnObject.GetChild(0).GetComponent<stomp>().controller

But if you are trying to get a prefab with GameObject.Find this will not work as it will only look for objects within the scene that are already instances(it will only check through the objects in the Hierarchy)

If you want to assign your variable a prefab you need to use:

 Resources.Load("folder/object");

Another post explains this:

http://answers.unity3d.com/questions/29876/how-can-i-assign-prefab-to-variable-without-drag-d.html

In your case I would do this:

 spawnObject.GetComponentInChildren<stomp> ().controller = Resources.Load ("PlayersFolderLocation/Player");


avatar image safak93 · Apr 20, 2014 at 02:21 PM 0
Share

You are the best thanks for everything, I appreciate it.

I have used this code:

 spawnObject.transform.GetChild (0).GetComponent<stomp> ().controller = GameObject.Find ("Player");

 
avatar image
1

Answer by OrbitSoft · Apr 18, 2014 at 09:44 PM

The Instantiate function returns the object you are instantiating so you can do the following:

 GameObject newEnemy = (GameObject)Instantiate(enemy,stuff);

Now you can acces its data normally:

 newEenemy.GetComponent<EnemyHealthController>().enemycount = someThing;
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 safak93 · Apr 18, 2014 at 10:21 PM 0
Share

I tried to do with this:

     void Spawn()
     {
         if(enemyCount <= 1)
         {
             enemyCount = 2;
             Instantiate(spawnObject,spawnPosition.position,Quaternion.identity);
             spawnObject.GetComponent<EnemyHealthController>().enemycount = GameObject.Find("EnemySpawn");
 
         }
 
 
     }

But i got this error:

 Assets/Scripts/EnemyCount.cs(31,75): error CS0029: Cannot implicitly convert type `UnityEngine.GameObject' to `EnemyCount'



EnemyCount.cs Script: using UnityEngine; using System.Collections;

 public class EnemyCount : $$anonymous$$onoBehaviour {
 
     public int enemyCount = 2;
     public GameObject spawnObject;
     public Transform spawnPosition;
 
     public HealthController healthController;
 
     // Use this for initialization
     void Start () {
 
     }
     
     // Update is called once per frame
     void Update () {
     if(enemyCount <= 1 && healthController.respawn)
         {
             Spawn();
         }
     }
 
     void Spawn()
     {
         if(enemyCount <= 1)
         {
             enemyCount = 2;
             Instantiate(spawnObject,spawnPosition.position,Quaternion.identity);
             spawnObject.GetComponent<EnemyHealthController>().enemycount = GameObject.Find("EnemySpawn");
         }
 
 
     }
 
 }
avatar image getyour411 · Apr 19, 2014 at 12:02 AM 0
Share

Don't do it like that, do it like the Answer syntax.

avatar image safak93 · Apr 19, 2014 at 02:44 PM 0
Share
 void Spawn()
     {
         if(enemyCount <= 1)
         {
             enemyCount = 2;
             GameObject newEnemy = (GameObject)Instantiate(spawnObject, spawnPosition.position, Quaternion.identity);
             newEnemy.GetComponent<EnemyHealthController>().enemycount = GameObject.Find("EnemySpawn");
         }
     }


Is the same error:

 Assets/Scripts/EnemyCount.cs(33,72): error CS0029: Cannot implicitly convert type `UnityEngine.GameObject' to `EnemyCount'
avatar image Loius · Apr 19, 2014 at 03:05 PM 0
Share

You cannot assign a gameobject to enemy count! It's not a gameobject variable. You can only assign an EnemyCount to it.

If your gameobject has an EnemyCount component then you have to Gameobject.Find("enemyspawn").GetComponent()

avatar image safak93 · Apr 19, 2014 at 03:28 PM 0
Share

a gameobject called "EnemySpawn" has the EnemyCount component. alt text

That means there is no solution for this, right?

unbenannt5.png (22.8 kB)

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

25 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

Related Questions

How to force a variable to prefab 1 Answer

Variable not Assigned 1 Answer

how to set custom parameters to GameObjects and access them? 1 Answer

The variable othertransform of Prefab has not been assigned 2 Answers

Why is transform.position of a prefab that's been instantiated different than a gameobject created on the scene, when they are in the exact same position? 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