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 S3dition · May 19, 2013 at 01:18 AM · gameobjectfunctionarraysfind

Loading function into array using GameObject.Find

Hey, I've been searching for a solution to this for a while, but I can't seem to find quite what I'm looking for.

I'm trying to loop through a script loaded on other objects and load the scripts into arrays to use later on. The problem is that GameObject.Find wants to use the function immediately, and won't store WeaponStats for future use. I've tried GameObject.Find() and transform.FindChild() without success. Obviously GameObject isn't going to work, but I get even more errors if I cast it as anything else. There must be a way to do this without declaring another variable or using a Find function on update (would destroy performance).

Or do I have to use GameObject.Find(object); and then call GetComponent?

    using UnityEngine;
     using System.Collections;
     
     public class Player : MonoBehaviour {
     
     private WeaponStats[] weaponBay = new WeaponStats[3];
     
     void Start(){
     
     weaponBay = new weaponBay[3];
     
             int g = 0;
             
     
                 while(g <= 2){
                 GameObject weapon = Instantiate(Resources.Load("Weapons/Smallcannon"), transform.position, transform.rotation) as GameObject;
                     weapon.transform.parent = transform;        
                     weapon.name = "weaponLoad" + g;
                     weaponBay[g] = GameObject.Find(weapon.name);
                     g++;
                 }
     }
     
         void FireWeapons(){
             
                 int i = 0;
                 while(i <= 2){
                 
             weaponBay[i].GetComponent().FireWeapon(weaponHardpoint[i]);
     
             }
     
     
         public void FireWeapon(Vector3 firePoint){
         
                 if(Time.time >= loadWeapon){
                  loadWeapon = Time.time + 60 / rateOfFire;
                 
                 //Fire Projectile            
                 //cannonVector = new Vector3(Vector3(fir);
                 audio.PlayOneShot(soundFX);    
         
                 Projectile zProjectile = Instantiate (projectile, firePoint, Quaternion.identity) as Projectile;
                 
                 //Pass weapon stats on to projectile
                 zProjectile.damage = Random.Range(weaponMinDamage,weaponMaxDamage);
                 zProjectile.ion = Random.Range(weaponMinIon,weaponMaxIon);
                 zProjectile.velocity = projectileVelocity;
                 zProjectile.attackType = attackType;
             }
         
         }
Comment
Add comment · Show 4
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 AlucardJay · May 19, 2013 at 01:31 AM 0
Share

I'm struggling to understand your question.

$$anonymous$$ain Script :

 var monsters : $$anonymous$$onsterScript[]; // an array that is typecast to the name of a script
 
 function Start()
 {
     monsters = new monsters[1];
     
     monsters[0] = GameObject.Find( "$$anonymous$$onster_1" ).GetComponent( $$anonymous$$onsterScript );
 }
 
 function Update()
 {
     if ( Input.Get$$anonymous$$ouseButtonDown(0) )
     {
         monsters[0].DoStuff();
     }
 }

$$anonymous$$onsterScript :

 function DoStuff()
 {
     Debug.Log( "Doing Stuff !" );
 }
avatar image S3dition · May 19, 2013 at 02:00 AM 0
Share

Sorry, my code didn't make it in on the first try.

To rephrase, I'm making a new child on the player's ship. Then I need to load the weapon into an array so it can be fired without looking up the weapon again. Because the weapon has important stats on it, I need that specific instance of the weapon, not just the script.

The result is always null.

I hope that clears it up a bit.

avatar image S3dition · May 19, 2013 at 02:31 AM 0
Share

Perhaps I should add a unique tag to each weapon and just use FindByTag?

avatar image S3dition · May 19, 2013 at 03:27 AM 0
Share

Attempted to mirror your code, but received "WeaponStats is a type but is used like a variable" error

1 Reply

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

Answer by AlucardJay · May 19, 2013 at 03:55 AM

You already have a reference to the gameObject when you instantiate it. From that gameObject, use GetComponent to store a reference to the script in your array, then you can call the function on that script :

 using UnityEngine;
 using System.Collections;
 
 public class Player : MonoBehaviour {
 
     private WeaponStats[] weaponBay = new WeaponStats[3];
 
     void Start(){
 
         weaponBay = new weaponBay[3];
 
         int g = 0;
 
         while(g <= 2){
             GameObject weapon = Instantiate(Resources.Load("Weapons/Smallcannon"), transform.position, transform.rotation) as GameObject;
             weapon.transform.parent = transform;        
             weapon.name = "weaponLoad" + g;
             //weaponBay[g] = GameObject.Find(weapon.name); // you already have a reference to the gameObject (weapon) when you instantiated it, here you want to store a reference to the script
             weaponBay[g] = weapon.GetComponent< WeaponStats >();
             g++;
         }
     }
 
     void FireWeapons(){
 
         int i = 0;
         while(i <= 2){
             //weaponBay[i].GetComponent().FireWeapon(weaponHardpoint[i]); // a reference to the script is stored, just call the function
             weaponBay[i].FireWeapon(weaponHardpoint[i]);
         }
     }
 }

Function you're trying to reference :

 public void FireWeapon(Vector3 firePoint){
 
     if(Time.time >= loadWeapon){
          loadWeapon = Time.time + 60 / rateOfFire;
         
         //Fire Projectile            
         //cannonVector = new Vector3(Vector3(fir);
         audio.PlayOneShot(soundFX);    
 
         Projectile zProjectile = Instantiate (projectile, firePoint, Quaternion.identity) as Projectile;
         
         //Pass weapon stats on to projectile
         zProjectile.damage = Random.Range(weaponMinDamage,weaponMaxDamage);
         zProjectile.ion = Random.Range(weaponMinIon,weaponMaxIon);
         zProjectile.velocity = projectileVelocity;
         zProjectile.attackType = attackType;
     }
 }


C# is not my native language, but this seems logically correct.

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


Please format your code. You can do this by highlighting all your code, then clicking the 10101 button at the top of the edit window.

  • Read this page : http://answers.unity3d.com/page/newuser.html

  • Watch : http://video.unity3d.com/video/7720450/tutorials-using-unity-answers

Comment
Add comment · Show 3 · 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 S3dition · May 19, 2013 at 04:06 AM 0
Share

Sorry, I was trying to do that earlier by manually adding the ` tags.

But I got that issue solved:

 weaponBay[g] = GameObject.Find(weapon.name).GetComponent("WeaponStats") as WeaponStats;

The issue stemmed from returning GameObject when it was wanting WeaponStats.

Thanks for the help though! Now I just need to figure out why my other array is blowing up. That's a problem for another day though.

avatar image AlucardJay · May 19, 2013 at 04:13 AM 0
Share

You already have a reference to the gameObject when you instantiated it, you don't need to then find it before GetComponent :

 weaponBay[g] = GameObject.Find(weapon.name).GetComponent("WeaponStats") as WeaponStats;

is the same as :

 weaponBay[g] = weapon.GetComponent< WeaponStats >();

Try to avoid using strings if possible.

http://docs.unity3d.com/Documentation/$$anonymous$$anual/GenericFunctions.html

avatar image S3dition · May 19, 2013 at 04:53 AM 0
Share

Ah, yeah, that's way easier than recasting the GameObject. Thanks!

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

14 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

Related Questions

How can I get every other GameObject except for the one I'm using? 1 Answer

Finding the angle between two GameObjects 1 Answer

Find 2D Texture via Script to use in Static Function 2 Answers

Function to locate game object with smaller distance to target makes the game lag - UnityScript 1 Answer

Locate a game object using rays 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