Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
2 captures
12 Jun 22 - 14 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 rainbowbeansprout · Nov 08, 2019 at 01:08 PM · prefabnullreferenceexceptiongetcomponent

Calling GetComponent on an instantiated prefab returns null,Calling GetComponent on an instantiated prefab

This seems to be a common problem but I haven't found a solution to it yet.

I'm trying to create an enemy that can shoot projectiles at the player, so the projectile is a prefab which has a script named "attack" with the public method "shoot", and the enemy script has a public variable with the prefab GameObject Attack. Whenever I instantiate a new Attack GameObject atk then call atk.GetComponent() it returns null.

This only happens specifically with instantiated prefabs. When I use an Attack GameObject that's already on the scene I'm able to get the attack script. It also seems to only apply to scripts, since calling GetComponent on any pre-built components like Rigidbody2D was successful.

Edit: example code that doesn't work

 public class Enemy : MonoBehaviour
 {
   public GameObject attack; //the Attack prefab
   
   void Start() {}
   void Update() {}
   
   void spawnAttack()
   {
     GameObject a = Instantiate(attack, transform.position, Quaternion.identity);
     a.GetComponent<AttackScript>().shoot(new Vector2(10f, 10f)); // this gets null reference exception
   }
 }
 
 public class AttackScript : MonoBehaviour
 {
   Rigidbody2D rb;
   
   void Start()
   {
     rb = GetComponent<Rigidbody2D>();
   }
   void Update() {}
 
   public void shoot(Vector2 direction) {
     rb.velocty = direction;
   }
 }

code that does work:

 // this works:
 public GameObject attack; //the GameObject I dragged on-screen
 
 void Start() {
   attack.GetComponent<AttackScript>().shoot(new Vector2(10f, 10f));
 }
 
 // this also works:
 public GameObject attack; //the Attack prefab
 
 void spawnAttack() {
   GameObject a = Instantiate(attack, transform.position, Quaternion.identity);
   a.GetComponent<Rigidbody2D>().velocity = new Vector2(10f, 10f);
 }
Comment
Add comment · Show 8
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 Casiell · Nov 08, 2019 at 03:07 PM 0
Share

Post your code please, it will be a lot easier

avatar image rainbowbeansprout Casiell · Nov 08, 2019 at 03:56 PM 0
Share

Thanks, I added example code.

avatar image Hellium · Nov 08, 2019 at 04:00 PM 0
Share

Try forcing the type of the prefab to have a Attack component

  public class Enemy : $$anonymous$$onoBehaviour
  {
    public AttackScript attack; //the Attack prefab
    
    void spawnAttack()
    {
      AttackScript a = Instantiate(attack, transform.position, Quaternion.identity);
      a.shoot(new Vector2(10f, 10f));
    }
  }
avatar image rainbowbeansprout Hellium · Nov 08, 2019 at 04:07 PM 0
Share

It looks like this would just create a new instance of the script object. I want to instantiate a new attack GameObject with attached sprite, collider, etc. Is there a way to force the type without sacrificing that?

avatar image Hellium rainbowbeansprout · Nov 08, 2019 at 04:08 PM 0
Share

No, you will provide the prefab in the inspector, and calling Instantiate will duplicate the whole object with all the other components and children.

Show more comments

1 Reply

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

Answer by Bunny83 · Nov 08, 2019 at 07:28 PM

Well the exact NullReference Exception would actually help. Because it's most likely not the call to shoot() that is causing the NullReference exception but inside shoot your access to velocity because your variable "rb" is null.


You initialize "rb" inside Start. However Start is called before the next Update callback is called. So it will of course not be called between your call of Instantiate and your shoot() call. Therefore rb is still null when you call shoot(). You should use Awake to initialize such internal references. However it would actually be easier to make the rb variable public and assign the reference in the inspector of the prefab. That way you don't need the GetComponent call at all.


Note that Awake will be called immediately when the object is created. So it will be called from inside the Instantiate call or when created dynamically from inside the AddComponent call. That means Awake will be finished before Instantiate returns and therefore before you call shoot().


Note that if this doesn't solve your issue, then your AttackScript is not attached to the root object of your prefab. GetComponent will only look for components on that gameobject, not for components on nested child objects.

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 rainbowbeansprout · Nov 08, 2019 at 08:55 PM 0
Share

That was exactly it, thank you! I added the Rigidbody as a public variable and that solved the issue.

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

153 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 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 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 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 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 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 avatar image avatar image avatar image

Related Questions

Help how to reference prefab for instantiating between loads. 0 Answers

NullReferenceException when using GetComponent to access script variables 1 Answer

NullReferenceException - Editor script using GetComponent after AddComponent 1 Answer

Possible Bug in Unity 5.4.1? NullReferenceException in console but everything works as expected (no old logs) 0 Answers

Access a function of an instantiated prefab 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