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 Wakeful · Jun 16, 2014 at 06:21 AM · c#2dgetcomponent

GetComponent giving error

I am starting to make a script that holds all the changeable values and use GetComponent to access them. I have looked at allot of other tutorials, even the unity one but I still cant figure it out. I am getting the error:

 NullReferenceException: Object reference not set to an instance of an object
 Enemy.FixedUpdate () (at Assets/_Scripts/Enemy.cs:29)

Here is my value storage script:

 using UnityEngine;
 using System.Collections;
 
 public class gameStats : MonoBehaviour {
     public int orcHealth;
     public int weaponShortSwordMinDamage;
     public int weaponShortSwordMaxDamage;
     // Use this for initialization
     void Start () {
     
     }
     
     // Update is called once per frame
     void Update () {
     
     }
 }

And my Orc script:

 using UnityEngine;
 using System.Collections;
 
 public class Enemy : MonoBehaviour {
     Animator anim;
     //public float health = 100;
     public bool canDamage = true;
     public float damageTimer;
     public float damageTimerOriginal;
 
     private gameStats Stats;
 
 
     // Use this for initialization
 
     void Awake ()
     {
         Stats = GetComponent<gameStats>();
     }
 
     void Start () {
         anim = GetComponent<Animator>();
 
 
     }
     //Used to see if the Orc is dead
     void FixedUpdate () 
     {
         if(Stats.orcHealth < 1)
         {
             anim.SetTrigger("Dead");
             
             
     
         }
         if(canDamage == false)
         {
             damageTimer = damageTimer - Time.deltaTime;
         }
         if(damageTimer < 0)
         {
             canDamage = true;
             damageTimer = damageTimerOriginal;
         }
     }
 
     
     // Update is called once per frame
     void OnTriggerEnter2D(Collider2D other) {
         if (other.tag == "WSS" && canDamage == true)
         {
             Stats.orcHealth = Stats.orcHealth - 10;
             //Leaveing this out for now:
             //Random.Range(WSSMinDamage, WSSMaxDamage);
             Debug.Log(Stats.orcHealth);
             canDamage = false;
         }
     }
 
 }


BTW I am working in 2D

Here is a view of my game so far, maybe you can spot a problem.

alt text

Thanks for the help :)

screenshot (42).png (163.4 kB)
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
3
Best Answer

Answer by ejpaari · Jun 16, 2014 at 06:34 AM

You are trying to get the Game Stats -component of the Enemy-object even though the component is in the Stats-object.

Following code tries to access the component of the same object (in this case, Enemy-object's Stats-component)

Stats = GetComponent();

but you could use instead, for example

Stats = GameObject.Find("Stats").GetComponent();

or some other method. On the other hand you could attach the Stats-object to your Enemy-object depending how you are designing your game.

Comment
Add comment · Show 1 · 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 Wakeful · Jun 16, 2014 at 05:53 PM 0
Share

Thanks guys for the help but now im getting the error:

 Assets/_Scripts/Enemy.cs(18,50): error CS0411: The type arguments for method `UnityEngine.GameObject.GetComponent<T>()' cannot be inferred from the usage. Try specifying the type arguments explicitly


$$anonymous$$y enemy script looks like this now:

 using UnityEngine;
 using System.Collections;
 
 public class Enemy : $$anonymous$$onoBehaviour {
     Animator anim;
     //public float health = 100;
     public bool canDamage = true;
     public float damageTimer;
     public float damageTimerOriginal;
 
     private gameStats Stats;
 
 
     // Use this for initialization
 
     void Awake ()
     {
         Stats = GameObject.Find("Stats").GetComponent();
     }
 
     void Start () {
         anim = GetComponent<Animator>();
 
 
     }
     //Used to see if the Orc is dead
     void FixedUpdate () 
     {
         if(Stats.orcHealth < 1)
         {
             anim.SetTrigger("Dead");
             
             
     
         }
         if(canDamage == false)
         {
             damageTimer = damageTimer - Time.deltaTime;
         }
         if(damageTimer < 0)
         {
             canDamage = true;
             damageTimer = damageTimerOriginal;
         }
     }
 
     
     // Update is called once per frame
     void OnTriggerEnter2D(Collider2D other) {
         if (other.tag == "WSS" && canDamage == true)
         {
             Stats.orcHealth = Stats.orcHealth - 10;
             //Leaveing this out for now:
             //Random.Range(WSS$$anonymous$$inDamage, WSS$$anonymous$$axDamage);
             Debug.Log(Stats.orcHealth);
             canDamage = false;
         }
     }
 
 }
 




avatar image
2

Answer by phxvyper · Jun 16, 2014 at 06:38 AM

Ejpaari is correct. However, for efficiency's sake, attach the GameStats component to the player, as there is no real reason for it to be attached to a separate empty object!

Once you do this, you can use GetComponent(); or GetComponent(typeof(gameStats)); to find that instance of the gameStats component on your player!

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 hayer · Jun 17, 2014 at 09:33 AM

Since you are using C# I would suggest using the more "C#ish" version; GetComponent where the is a generic type which inherits from Component. So if you want to get a SpriteRenderer you would write;

 SpriteRenderer srInstance = gameObject.GetComponent<SpriteRenderer>();

To get the SpriteRenderer of the gameObject the script is attached too. This can also be used like this;

   SpriteRenderer srInstance = GameObject.Find("MyGameObject").GetComponent<SpriteRenderer>();

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 hayer · Jun 17, 2014 at 09:17 AM 0
Share

Seems like the formatting for the 2nd code snippet is broken.

avatar image meat5000 ♦ · Jun 17, 2014 at 09:34 AM 0
Share

Always leave an extra line between code and text :)

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

6 People are following this question.

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

Related Questions

Multiple Cars not working 1 Answer

Distribute terrain in zones 3 Answers

how to use bool from another script in if statment? 2 Answers

Is there a way to find other's components using OnTriggerEnter? 1 Answer

if it's you, how will you solve it ? 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