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 /
This post has been wikified, any user with enough reputation can edit it.
avatar image
0
Question by digzou · Jan 19, 2015 at 02:41 PM · c#javascriptinstantiatenullreferenceexceptionunassignedreferenceexcept

Attach script twice.

I have implemented a simple 2d game in unityscript. I have a prefab with RigidBody2D,Circle Collider2D and a script attached to it[else doesnt perform simple lerp also]. In the scene I have created an empty game object and attached the same script and rigidbody2d. The script instantiates the prefab itself, which I attach in the inspector. Worked perfectly.

I am now translating the whole project into C#. But when I follow the similar steps as above, I get an error of UnassignedReferenceException and NullException. I know that it is caused because, I am not attaching anything to the script that I have attached to the prefab. But attaching anything to the prefab script causes more errors and seems wrong. Is there some fundamental rule that I have missed?

 using UnityEngine;
 using System.Collections;
 
 public class blobScript : MonoBehaviour {
 
     private sceneManagerScript scenemanager;
 
     public GameObject blobPrefab;         //Add from inspector.
     private GameObject blobobj;             //Instantiate the blob prefab to this object.
     public GameObject tutArrow;            //Tutorial arrow prefab.
 
 
     private GameObject[] tutobjs = new GameObject[3];
     private float[] tutPositions = new float[3]{3.1f,2.7f,2.3f};
 
     /*****Vectors*****/
     private Vector2 tempBlobScale;        //Tempvariable since blobobj's transform cannot be modified directly in C#.
     private Vector2 mouseDownPos;
     private Vector2 mouseUpPos;
     private Vector2 newPosition;
     private Vector2 v2delta;
     private Vector2 tempNewPosition;
 
     /*****INTEGERS*****/
     private static int SCORE;
     private static int LIVES;
 
     /*****Flags*****/
     private bool blobSet;
     private bool blobScaledUp;
     private bool CORRECT;
     private bool isCorrectWallSet;
     private bool diamondAnimation;
     private bool tutorialset;                  //Start the tutorial.
     private bool tutAnimating;                 //Start the animation.
     private bool[] animTutArrows= new bool[3]; //Used to animate the tutorial.
 
     private Color tempColor;
 
 
     //CORRECT MOVE OR NO
     public enum SWIPE {
         RIGHT,
         TOP,
         LEFT,
         BOTTOM
     }
     
     public SWIPE Swipe;
 
 
     void Start(){
         scenemanager=GameObject.Find("SceneManager").GetComponent<sceneManagerScript>();
         tempBlobScale=Vector2.zero;
         blobSet=false;
         blobScaledUp=false;
         CORRECT=false;
         tutorialset=false;
         SCORE=0;
 
         LIVES = PlayerPrefs.GetInt("LIVES");
     }
 
     void Update(){
         if(scenemanager.isState(sceneManagerScript.GAMESTATE.INITIALIZE)){
             if(!blobSet){initBlob();} //<<--UNASSIGNED REFERENCE ERROR    
             if(blobSet){scaleUpBlob();}
         }
 
         if(scenemanager.isState(sceneManagerScript.GAMESTATE.PLAY)){
             if(SCORE==0){
                 if(!tutorialset){
                     setTutorial();
                 }else{setTutorialAnim();}                                             //Start animating the tutorial.
             }
 
             newPosition=Vector2.zero;
 
             if (Input.GetMouseButtonDown (0)) {
                 Debug.Log("MOUSE DOWN!!");
                 mouseDownPos = Input.mousePosition;} //Save position when Screen Touched.
 
             if (Input.GetMouseButtonUp (0)) {
                 Debug.Log("MOUSE UP!!");
                 mouseUpPos = Input.mousePosition;                            // api call to give the last position// user touched/mouse down
 
                 v2delta = mouseUpPos - mouseDownPos;               // difference between them
                 
                 if (v2delta.normalized.x >= CONSTANTS._TOUCHTHRESHOLD) {                     
                     newPosition.x = CONSTANTS._DISTANCE; 
                     changeSwipeTo(SWIPE.RIGHT);
                     Debug.Log("Swipe is : "+Swipe);
                 } else if (v2delta.normalized.x <= CONSTANTS._TOUCHTHRESHOLD) {                    
                     newPosition.x = -(CONSTANTS._DISTANCE);  
                     changeSwipeTo(SWIPE.LEFT);    
                     Debug.Log("Swipe is : "+Swipe);
                 } else if (v2delta.normalized.y <= CONSTANTS._TOUCHTHRESHOLD) {                    
                     newPosition.y = -(CONSTANTS._DISTANCE); 
                     changeSwipeTo(SWIPE.BOTTOM);
                     Debug.Log("Swipe is : "+Swipe);
                 } else if (v2delta.normalized.y >= CONSTANTS._TOUCHTHRESHOLD) {                    
                     newPosition.y = CONSTANTS._DISTANCE;
                     changeSwipeTo(SWIPE.TOP);
                     Debug.Log("Swipe is : "+Swipe);
                 } 
             }
             if(newPosition!=Vector2.zero){
                 if(Swipe.ToString().Equals(scenemanager.getCorrectWall().ToString())){
                     
                     tempNewPosition=newPosition;
                                                                                     
                     scenemanager.changeStateToSwiped();
                     mouseUpPos = Vector3.zero;
                     v2delta = Vector2.zero;
                 }else if(LIVES > 0){
                     
                     scenemanager.changeStateToWrongmove();
                     
                 }
                 else{
                     
                     tempNewPosition=newPosition;
                                                                                                 scenemanager.changeStateToWrongmove();
                     mouseUpPos = Vector3.zero;
                     v2delta = Vector2.zero;
 
                 
                     
                 }
             }
         }
     }
 
     void FixedUpdate(){
         if(scenemanager.isState(sceneManagerScript.GAMESTATE.SWIPED)){
             blobobj.transform.position = Vector2.Lerp (blobobj.transform.position, tempNewPosition, Time.deltaTime*7); //<<--NULL REFERENCE ERROR    
         }
     }
 
     /*This function instantiates the blob after the play button is pressed*/
     private void initBlob(){
         int randomIndex = Random.Range(0,4);                                                //To pickup a random color from the currentArrayOfColor[] in scenemanager.
         blobobj=(GameObject)Instantiate(blobPrefab,Vector2.zero,Quaternion.identity);
         blobobj.name=CONSTANTS._BLOBNAME;
         blobobj.renderer.material.color =scenemanager.currentArrayOfColor[randomIndex];     //Set random color.
         blobobj.renderer.material.shader=CONSTANTS._SHADER;
         blobobj.transform.localScale= Vector2.zero;                                            //Set scale to 0 since we have to scale up the blob.
         blobSet=true;
     }
 
     /*This function scales up the blob after it has been instantiated*/
     private void scaleUpBlob(){
         if(tempBlobScale.x<1.0f){tempBlobScale=blobobj.transform.localScale;}
         if(tempBlobScale.y<1.0f){
             tempBlobScale.x+=CONSTANTS._SCALEUPFACTOR;
             tempBlobScale.y+=CONSTANTS._SCALEUPFACTOR;
             blobobj.transform.localScale=tempBlobScale;
         }else{
             tempBlobScale.x=1.0f;
             tempBlobScale.y=1.0f;
             blobobj.transform.localScale=tempBlobScale;
             blobScaledUp=true;
         }
     }
 
    
     public bool isBlobScaledUp(){return blobScaledUp;}
     public bool getCORRECT(){return CORRECT;}
     public int getGain(){
         //TODO
         return 1;
     }
     public Color getColor(){return blobobj.renderer.material.color; }
     public GameObject getBlobObj(){return blobobj;}
 
     //Setters
     public void setCORRECT(bool flag){CORRECT = flag;}
     
     public void changeSwipeTo(SWIPE s){Swipe=s;}
 }

Thanks.

alt text alt text

prefab.png (57.0 kB)
gameobject.png (43.8 kB)
Comment
Add comment · Show 2
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 SaraCecilia · Jan 19, 2015 at 03:00 PM 0
Share

What part of your script is not working? Looks like you pasted in your entire code into this post.

avatar image digzou · Jan 20, 2015 at 06:48 AM 0
Share

Unassigned reference at line 66 and null exception at .35

Pasted the entire script, so that anyone can go about seeing what I'm implementing.

1 Reply

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

Answer by hav_ngs_ru · Jan 19, 2015 at 03:22 PM

  scenemanager=GameObject.Find("SceneManager").GetComponent<sceneManagerScript>();

check scenemanager value after this... I presume it stays null and causes second error...

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 hav_ngs_ru · Jan 19, 2015 at 03:35 PM 1
Share

... but generally your architecture looks strange for me... actually you have a blob-spawner (your empty object) wich only spawns one blob and has the same script as the blob...

if it needed to spawn many blobs - I'd prefer have the spawner object with it's own script, in this case you could link blob prefab to spawner script's public field in inspector and use it to instantiate blobs...

if you need only one blob (or finite amount of blobs set in scene when it was created) - you dont need a spawner at all - just drag a blob prefab on scene...

or I misunderstood your idea? :)

avatar image digzou · Jan 20, 2015 at 06:37 AM 0
Share

I checked for the scene manager to be null and it never is. I think I should try creating the blob without the spawner. New to unity. Will let you know if the advice worked for me. Thanks :)

avatar image digzou · Jan 20, 2015 at 09:03 AM 0
Share

Creating the blob without the spawner worked! I don't know how was it working with unityscript. Although the first answer directly couldnt solve the problem I'll mark your answer correct based on the second answer. :) Thanks!

avatar image pumpkinszwan · Jan 20, 2015 at 09:10 AM 0
Share

Does the Scene$$anonymous$$anager GameObject actually have a scene$$anonymous$$anagerScript instance attached?

avatar image digzou · Jan 20, 2015 at 09:37 AM 0
Share

@pumpkinszwan Yes it does have a scene$$anonymous$$anagerScript attached. $$anonymous$$y problem was I was attaching the blobscript to the prefab as well as the empty game object and I was attaching gameobject references to the empty gameobject only and not on the prefab. I did know something was wrong in attaching the script at two places, but it worked somehow when using it in unityscript, but C# invoked errors. :)

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

27 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

Related Questions

Instantiate giving a NullReferenceError 1 Answer

Instantinate NullReferenceError problem 0 Answers

AddForce NullReferenceException 1 Answer

Distribute terrain in zones 3 Answers

NullReferenceException and m_InstanceID == 0 on LoadLevel (C#) 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