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 maggot · Dec 23, 2011 at 01:35 PM · c#arrayvalueget

Sending value stored in an array to another script with cSharp

Using cSharp, with Player001Controls.cs I am sending the value shootForce stored in an array to another script MoveMissile.cs . The array element is determined by missileSelection. I have it working with this :

Player001Controls.cs

 public class Bullet {
   public int missileSelection;     // Current missile selected
   public int missileVariety;    // Total types of missile variety (max size of array)
   public float[] shotForce; 
   public void InitializeBullets() 
   { 
         missileSelection = 0;
         missileVariety = 4;
         shotForce = new float[missileVariety];
            shotForce[0] = 1.5f;
          shotForce[1] = 20f;
         shotForce[2] = 30f;
         shotForce[3] = 40f;
         shootForce = shotForce[missileSelection]; 
   }
 }

missileSelection is called from a method in class Player001Controls and the value determined by user input (right mouse button click increments missileSelection) and constrained to array size of missileVariety. However code as it is means of course that missileSelection is 0 whenever shootForce is sent or read from.

I have it working in class Player001Controls with :

 public class Player001Controls : MonoBehaviour
 {   
     public Bullet B = new Bullet();
     public void Awake()
     {
         B.InitializeBullets();
     }
     
     public void OnGUI() 
     {
             GUI.Label(new Rect (10, 60, 300, 20),"Power of shot: " + B.powerOfShot);
     }
 }

Where would I put shootForce = shotForce[missileSelection] in order for it to read the shotForce array stored in InitializeBullets() and return a value determined by pointer missileSelection to another script (mine is called moveMissiles.cs) ?

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

3 Replies

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

Answer by maggot · Dec 24, 2011 at 12:47 PM

Here is how I got the value for shootSpeed sent from Player001Controls.cs to MoveMissile.cs

Player001Controls.cs

 public class Player001Controls : MonoBehaviour
 { 
     public float shootSpeed
     {
         get{_shootSpeed = Bullet.shotForce[missileSelection];
             return _shootSpeed;}
         set{_shootSpeed = value;}
     }
     private float _shootSpeed;
 
     public void Awake()
     {        
         Bullet.InitializePlayerBullets();
     }
 }

MoveMissile.cs

 public class MoveMissile : MonoBehaviour
 {
     private float missileSpeed; 
 
     public void Awake()
     {
         Player001Controls PC = (Player001Controls)GameObject.Find("Player001Character").GetComponent("Player001Controls");
         missileSpeed = PC.shootSpeed;
      }
 
      void FixedUpdate () 
      {

          rigidbody.velocity = transform.up * missileSpeed;
      }
 }

Player001Controls.cs is attached to the Player001Character object.

MoveMissile.cs is attached to the missile object that is fired by Player001Character

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
2

Answer by Bunny83 · Dec 23, 2011 at 02:25 PM

Ok, from a design point it looks strange to have a bullet class (which obviously represents a single bullet) and see a member function InitializeBullets. I guess the shotForce array should be the same for each bullet? That's usually something where you could use static variables. static variables are tied to the class and not a single instance, so they are the same for each bullet.

 public class Bullet
 {
     // member variables / functions
     public int type;  // bullet type
     public float ShootForce
     {
         get
         {
             if (type < 0 || type >= missileVariety)
                 return 0.0f;  // Maybe print a warning with Debug.LogWarning()
             return shotForce[type];
         }
     }
     // constructor
     public Bullet(int aBulletType)
     {
         type = aBulletType;
     }
 
 
     // static variables / functions
     public static int missileVariety;    // Total types of missile variety (max size of array)
     public static float[] shotForce; 
     public static void InitializeBullets() 
     { 
         missileVariety = 4;
         shotForce = new float[missileVariety];
         shotForce[0] = 1.5f;
         shotForce[1] = 20f;
         shotForce[2] = 30f;
         shotForce[3] = 40f;
     }
 }

To initialize the static variables just call InitializeBullets once. Now when you create an instance of your bullet you have to specify the type. The ShootForce property will return the required force according to the bullet type

 public class Player001Controls : MonoBehaviour
 {   
     public int currentMissile = 0;
     public void Awake()
     {
         Bullet.InitializeBullets();
     }
 
     public void Update() 
     {
         if (Input.GetMouseButtonDown(0))
         {
             Bullet B = new Bullet(currentMissile);
             // Use B.ShootForce for the new bullet
         }
     }
 }

This is a typical OOP example. However, in Unity you usually have MonoBehaviours which are attached to GameObjects. Those scripts / classes can't be created with new and can't have a custom constructor. If you want to hold a seperate instance for the bullet you can do it that way i've mentioned, but it doesn't make much sense. Usually you want the class to represent a bullet during it's whole lifetime. Your bullets are usually prefabs (pre designed GameObjects) which are used to Instantiate (clone) a new bullet when needed. To support different bullets you would create an array of prefabs so you can easily select one of them. The different attributed of each bullet should be handled by a script on each bullet prefab. A simple example:

 // Bullet.cs
 public class Bullet : MonoBehaviour
 {
     public float launchForce; // assigned in the inspector
     void Start()
     {
         rigidbody.AddForce(0,0,launchForce); // add the force in forward direction
     }
 }
 
 // Player.cs
 public class Player : MonoBehaviour
 {
     public Bullet[] bullets; // assign the different bullet prefabs to this array
     public Transform bulletSpawnPoint; // assign the spawnpoint from your weapon
     public int currentBullet = 0;
     public void Shot()
     {
         Instantiate(bullets[currentBullet], bulletSpawnPoint.position, bulletSpawnPoint.rotation);
     }
 }
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 maggot · Dec 23, 2011 at 03:20 PM 0
Share

Yes, I had my version working with this :

shootForce = shotForce[Random.Range(0, 3)];

in initializeBullets()

Which fired a bullet from move$$anonymous$$issile.cs at velocity of shootForce given from the array position deter$$anonymous$$ed by Random.Range(0,3), so its firing bullets at random speeds.

The actual prefab is deter$$anonymous$$ed from other member functions in Player001Controls.cs

I tried changing public shotForce to public static shotForce which gave me errors from move$$anonymous$$issile.cs (fixed) I now have all Bullet class properties as static and replaced B. calls with Bullet. calls However I'm now having all the instantiated bullet speeds affected by changes in the value shootForce (wip).

I also removed missileSelection from Bullet, and put it into class Player001Controls.

I haven't gone through all your example code yet, but thanks so far

avatar image jahroy · Dec 23, 2011 at 04:42 PM 1
Share

If you use a static variable, its value will be used by all instances of the class.

If different bullets should be able to have different speeds, then you do not want the speed variable to be static.

It should be a normal, non-static variable, so each bullet can have its own speed.

This example is a GREAT demonstration of the difference between static and non-static vars.

avatar image maggot · Dec 23, 2011 at 05:40 PM 0
Share

I guessed as much, but how do I get the value for property public float shootForce (the velocity of the bullet) from Bullet to move$$anonymous$$issile.cs ?

From move$$anonymous$$issile.cs I can't use Bullet.shootForce as that only works for static variables.

avatar image jahroy · Dec 23, 2011 at 05:57 PM 0
Share

You need an instance of a bullet to access its instance (non-static) variables.

Here's another attempt to demonstrate the difference:

 class ExampleClass
 {
     /* a static var */

     static var static$$anonymous$$sg : String = "Hello from the class";

     /* instance variables */

     var name : String = "Object Number One";
     
     function sayHello () : void
     {
         print("Hello from the instance named: " + name);
     }    
 }

 function Start ()
 {
     /* print static var - no need for an instance */
  
     print(ExampleClass.static$$anonymous$$sg);

    
     /* create an instance to access instance vars */

     var theInstance : ExampleClass = new ExampleClass();

     theInstance.name = "Super Funky Instance";

     /* call a member function that will access the instance var */

     theInstance.sayHello();
 }
avatar image jahroy · Dec 23, 2011 at 06:25 PM 0
Share

I just added another answer which demonstrates what is, in my opinion, the easiest way to access an array in one script from another script.

The best way to learn stuff like this is to read the documentation. It's full of information!

avatar image
0

Answer by jahroy · Dec 23, 2011 at 06:24 PM

Here is an example of how you access an array from one script from another script.

// file name: ScriptOne.js

var theArray : float [] = new float [];

function Awake () { theArray = [ 3.14, 2.71, .074, .999 ]; }

// file name: ScriptTwo.js

/ you can assign the value of this variable to an instance of a ScriptOne object by dragging and dropping an object that has a ScriptOne attached to it into the Inspector onto the slot named "Instance Of ScriptOne" after selecting an object that has a "ScriptTwo" attached to it Step 1: attach this script to an object Step 2: select the object by left-clicking it Step 3: look in the Inspector Step 4: find a slot named "Instance Of Script One" Step 5: drag an object with a ScriptOne attached to it onto the slot /

var instanceOfScriptOne : ScriptOne;

function Start () { / check to see if you read my comment above /

 if ( ! instanceOfScriptOne ) {
     Debug.LogWarning("Please assign the instance in the Inspector");
     return;
 }

 /* print some values in the array from the ScriptOne script */

 for ( var i : int = 0; i &lt; 10; i ++ ) {
     print(instanceOfScriptOne.theArray[i]);
 }

}

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

7 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Store reference to array as variable 2 Answers

Assign gameobject value from an array (C#) 1 Answer

how subtract total value element of array ?? 1 Answer

How would I get an array value? 2 Answers

Get values from long string (C#) 5 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