Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 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 George-B · Jul 09, 2016 at 02:37 PM · c#unity 52dinstantiateprefab

Why is my Prefab Instantiating when the Scene is Loaded?

Hello! I am creating a 2D video game where a player can shoot a harpoon when the space bar is pressed, and can move left, right, up, and down using the arrow keys.

When I start my game, the prefab of the harpoon automatically instantiates, although the space bar has not been pressed yet.

Is there something wrong with my code? Do I need to change something in the inspector? What are some other reasons that the prefab instantiates on start? Thanks in advance- George :)

Here is my code-
harpoonScript.cs

 using UnityEngine;
 using System.Collections;
 using UnityEngine.UI;
 
 public class harpoonScript : MonoBehaviour {
 
 // Public variable 
 public int speed = 6;
 private Rigidbody2D r2d;
 public Text FishLabel;
 public int fishKillCount = 0;
 
 // Function called once when the bullet is created
 void Start () {
     // Get the rigidbody component
     r2d = GetComponent<Rigidbody2D>();
 
     // Make the bullet move upward
     float ySpeed = 0;
     float xSpeed = -8;
 
     Vector2 newVelocity = new Vector2(xSpeed, ySpeed);
 r2d.velocity = newVelocity;
 
 }
 
 void OnTriggerEnter2D(Collider2D other) //hero hits side of enemy
     {
         if (r2d = null) {
        Debug.Log("Unable to find GameObject, reference is null");
   } else {
 
              string fishStringfromText = FishLabel.text;
              int fishIntfromText;
              fishIntfromText = int.Parse(fishStringfromText);
 
   ++fishIntfromText;
 
   FishLabel.text = fishIntfromText.ToString();
 
        Debug.Log("GameObject found, reference is not null");
        Destroy(other.gameObject.GetComponent<Collider2D>()); //Remove collider to avoid audio replaying
             other.gameObject.GetComponent<Renderer>().enabled = false; //Make object invisible
             Destroy(other.gameObject, 0.626f); //Destroy object when audio is done playing, destroying it before will cause the audio to stop
     Destroy(GameObject.Find("harpoon_00001(Clone)"));
   }
 
 }
 
 
 }

playerMove.cs

 using UnityEngine;
 using System.Collections;
 
 public class playerMove : MonoBehaviour {
 
     // All Variables
     public float speed = 10;
     private Rigidbody2D rigidBody2D;
     private GameObject harpoon_00001;
     private bool facingRight = true;
 
     void Awake () {
 
         rigidBody2D = GetComponent<Rigidbody2D>();
         harpoon_00001 = GameObject.Find("harpoon_00001");
   if (harpoon_00001 == null) {
        Debug.Log("Unable to find GameObject, reference is null");
   } else {
        Debug.Log("GameObject found, reference is not null");
   }
 
     }
 
 void Update () {
 
     if (Input.GetKeyDown(KeyCode.LeftArrow) && !facingRight) {
         Flip();
     }
 
     if (Input.GetKeyDown(KeyCode.RightArrow) && facingRight) {
         Flip();
     }
 
 }
 
 void Flip () {
 
     facingRight = !facingRight;
 
     Vector3 theScale = transform.localScale;
     theScale.x *= -1;
     transform.localScale = theScale;
 
 }
 
     void FixedUpdate () {
 
         float xMove = Input.GetAxis("Horizontal");
         float yMove = Input.GetAxis("Vertical");
 
         float xSpeed = xMove * speed;
         float ySpeed = yMove * speed;
 
         Vector2 newVelocity = new Vector2(xSpeed, ySpeed);
 
         rigidBody2D.velocity = newVelocity;
 
         if (Input.GetKeyDown("space")) {
             GetComponent<AudioSource>().Play();
             
 harpoonScript harpoon = Instantiate(harpoon_00001,transform.position, Quaternion.identity) as harpoonScript;
 // Assuming harpoon prefab already facing to right
 
 if (facingRight) {
     
 harpoon.transform.eulerAngles = new Vector3(0f, 0f, 180f); // Face backward
   Vector3 theScale = harpoon.transform.localScale;
   theScale.x *= -1;
   harpoon.transform.localScale = theScale; // Flip on y axis
 }
 
 
     }
 
 }
 }



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

2 Replies

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

Answer by ScaniX · Jul 10, 2016 at 03:34 PM

If I understand correctly, you get your "prefab" from the scene with this line:

 harpoon_00001 = GameObject.Find("harpoon_00001");

GameObject.Find() only finds objects in the scene that are active, so I think the moon lady is correct when she says that you have that object in the editor scene.

If you want to have the prototype harpoon in the scene (in contrast to store the harpoon as a "real" prefab and drag it onto your member variable or use Resource.Load()), then set it as inactive and assign it to your script using the inspector by making the member variable public.

 public GameObject harpoon_00001;

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 George-B · Jul 22, 2016 at 04:43 PM 0
Share

@ScaniX- The harpoon does stop instantiating at the beginning when I delete it from then scene, but then another problem comes up. The harpoons can't destroy the fish if there isn't an instance of the harpoon on the scene, for some reason. Any ideas on how to fix that?

avatar image ScaniX George-B · Jul 22, 2016 at 04:54 PM 0
Share

Not really. If you did the following:

  • drag your scene harpoon to the prefab folder to store that instance with its scripts and other components

  • delete the instance in the scene

  • drag the prefab from the project explorer to your prefab field in the inspector

It should work. The harpoon should be instantiated from the prefab with all its scripts and work like before.

avatar image George-B ScaniX · Jul 22, 2016 at 05:22 PM 0
Share

I just did what you said, but the harpoon still doesn't kill the fish. Ins$$anonymous$$d, the console says this-

NullReferenceException: Object reference not set to an instance of an object harpoonScript.OnTriggerEnter2D (UnityEngine.Collider2D other) (at Assets/Levels/Scripts/harpoonScript.cs:30)

Show more comments
avatar image George-B · Jul 22, 2016 at 06:28 PM 0
Share

@ScaniX I put in the code from your newest comment, commented out the part about the fish label, and it works now! Thanks for your help!

avatar image
2

Answer by AnneSchmidt_legacy · Jul 10, 2016 at 02:02 PM

Are you sure you didn't leave an instance of the harpoon on the scene?

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

5 People are following this question.

avatar image avatar image avatar image avatar image avatar image

Related Questions

Instantied 2D Prefab Is Invisible 1 Answer

How to move Instantiated 2D objects by 0.5 using arrows 1 Answer

How to make TCG Deck (Instatiate based on Prefab) 1 Answer

Destroying assets is not permitted to avoid data loss. 0 Answers

How do I make a clone of a prefab appear on the correct layer? [5.2.2f1] 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