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 gdubrocks · May 06, 2014 at 10:56 PM · c#gameobject

Initializing objects with another scripts variables.

I want to start by saying I have read this page 10 times, so please don't just link it. http://docs.unity3d.com/412/Documentation/ScriptReference/index.Accessing_Other_Game_Objects.html

I have two scripts, playerStats, and gameManagment. Within gameManagment script I first initialize the other script with awake and then attempt to initialize some standard "players", attach the playerStats script to them. I now want to edit each players stat individually, but am having trouble doing so.

The gameManagment script is assigned to an empty gameobject within unity. I wish to give each new "player" object the playerStats script within gameManagment.

GameManagment script:

 public PlayerStats playerStats;
 
         void Awake()
     {
         playerStats = GetComponent<PlayerStats>();
     }
 
     void Start()
     {
         //create players
         GameObject player1 = GameObject.CreatePrimitive(PrimitiveType.Capsule);
         player1.transform.position = new Vector3(4,1,0);
         player1.AddComponent<PlayerStats>();
         player1.tag = "Player";
         //player1.PlayerStats.setSpeed(10);
                 //this line is my intended implementation, but will not compile
 
         GameObject player2 = GameObject.CreatePrimitive(PrimitiveType.Capsule);
         player2.transform.position = new Vector3(0,1,4);
         player2.AddComponent<PlayerStats>();
         player2.tag = "Player";
         //playerStats.setSpeed(5);
                 //this line compiles, but gives me a null reference exception 
                 //at runtime
     }
 
 PlayerStats script :
 
 public class PlayerStats : MonoBehaviour {
 
     public float speed = 0;
     public float health = 100;
     public bool dead = false;
     
     void Start(){
         speed = 0;
         health = 100;
     }
     
     public void setSpeed(float amount)
     {
         speed = amount;
     }        
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

1 Reply

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

Answer by robertbu · May 06, 2014 at 11:01 PM

AddComponent() returns a reference to the component, so you could replace/insert at line 13:

 PlayerStats ps1 = player1.AddComponent<PlayerStats>();
 ps1.setSpeed(15.0f);

While this is the best solution, you could also use GetComponent() to solve the problem. So anytime after you've added PlayerStats, you could do:

 PlayerStats ps1 = player1.GetComponent<PlayerStats>();

or if you are sure the component is there, you can create a compound statement:

 player1.GetComponent<PlayerStats>().setSpeed(11.0f);


I don't know if it will help you, but here is another reference page for GetComponent():

http://unitygems.com/script-interaction1/

Comment
Add comment · Show 2 · 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 gdubrocks · May 07, 2014 at 12:58 AM 0
Share

Thanks Robert! I have been puzzling over this all day and that worked great.

Are there any advantages to the compound statement?

avatar image robertbu · May 07, 2014 at 01:02 AM 0
Share

Compound statements make the code look a bit cleaner. They have two downsides. First, if there is any chance the 'GetComponet()' can fail (i.e. the component that you are seeking does not exist on the game object), then a compound statement will cause a null reference exception. The second issue is performance. While not a huge deal, GetComponent() does have some cost. If you are going to be referencing a component every frame, then you would want to declare a variable at the top of the class, then initialize that variable in Start(). That way you could use do ps1.setSpeed() or whatever each frame without calling GetComponent().

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

21 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

Related Questions

Assigning a gameObject in the script 3 Answers

Distribute terrain in zones 3 Answers

Multiple Cars not working 1 Answer

Problem with taking a gameobject from gameobject list to inventory. 1 Answer

Glow single Object 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