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
2
Question by orv · Mar 16, 2010 at 01:56 PM · errorvariablenullreferenceexceptionfunctionreference

How to call a function from another script - getting error "Object reference not set to an instance of an object"

Im having a problem calling a function from another script.

Ive looked around and came up with THIS and THIS, but I cant to get it to work.

I want to call the function AddScore() located in ScoreTextScript.js from BallHitTarget.js

BallHitTarget.js

var scriptName : ScoreTextScript;

function Update () { scriptName.AddScore(); }

ScoreTextScript.js

var score : int = 0;

function Update()

{

guiText.text = "Score: " + score;

}

function AddScore()

{ score ++;

}

I keep getting the error "NullReferenceException: Object reference not set to an instance of an object BallHitTarget.Update () (at Assets\Standard Assets\Scripts\BallHitTarget.js:6)" with line 6 being scriptName.AddScore();

Comment
Add comment · Show 1
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 Balint · Nov 17, 2013 at 02:46 PM 0
Share

Oh. I have the same trouble... in pinball... but I use C#.

5 Replies

· Add your reply
  • Sort: 
avatar image
11
Best Answer Wiki

Answer by davebuchhofer · Mar 16, 2010 at 03:04 PM

JS not being my strong point, so i'm sure someone else will chime in, but may i suggest that you're creating a new instance of ScoreTextScript not retrieving the one in use in the scene currently

Doc wise, this would be the one for direct calling: http://unity3d.com/support/documentation/ScriptReference/GameObject.GetComponent.html

psuedo code but, if you want to stay with the same type of system, you may just want to

//you would place the object that has the ScoreTextScript on it ///in this var slot in the inspector

var scriptName : GameObject;

..... //and access it via scriptName.GetComponent(ScoreTextScript).AddScore();

if you're looking to build something a little more reusable and flexibile, i'd say look into one of the Messaging systems, http://technology.blurst.com/unityscript-messaging-system/ for javascript, or http://www.unifycommunity.com/wiki/index.php?title=CSharpMessenger_Extended for c# its a bit more of an initial learning curve, but a lot more flexible in the long run

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 orv · Mar 16, 2010 at 03:50 PM 0
Share

Awesome! Worked perfectly for me. Thanks

avatar image
2

Answer by duck · Mar 16, 2010 at 03:25 PM

This sounds like you've created the public reference variable, but you haven't actually assigned the reference. It's possible to do this with scripting, using GetComponent, however this is a task ideally suited to Unity's Dragged References.

First of all, are both scripts each placed on their respective GameObjects in the scene? I.E. presumably "BallHitTarget" should be placed on some sort of 'target' GameObject, and ScoreTextScript should be placed on a GameObject which has a GUIText component attached.

If so, it sounds like you may have just missed the last simple step which is to drag a reference from the Score Text object into the "ScoreTextScript" variable slot, on the target object.

To do this:

  • Select the target object
  • Now look at the BallHitTarget script in the inspector - you should see the variable 'scriptName' visible there*
  • Now drag the Score Text object from your hierarchy into that variable.

This creates a reference to the specific instance of "ScoreTextScript" which is attached to that gameobject.

By the way, "scriptName" isn't a very appropriate name for this var, and therein probably lies some of your confusion.

You might want to consider renaming the "scriptName" var to something which better suits its contents, such as "scoreManager", and perhaps you should even rename the ScoreTextScript itself to "ScoreManager" (with a captial S, to fit Unity's scripting conventions) - since it also keeps track of the score as well as just displaying it.

Your final scripts would then look like this:

BallHitTarget.js

var scoreManager : ScoreManager;

function Update () { scoreManager.AddScore(); }

ScoreManager.js

var score : int = 0;

function Update() { guiText.text = "Score: " + score; }

function AddScore() { score ++; }

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
0

Answer by djary · Jun 22, 2013 at 04:12 PM

hi , i problem too

i have script : MoneySystem.js

pragma strict static var money : int = 0 ; // for money systemfunction

function Update() { Debug.Log(money);

}

function AddMoney() { money = money + 20 ; Debug.Log(money);

}

and other script have : CharacterDamej.js

 var hitPoints = 100.0;
 var deadReplacement : Transform;
 var dieSound : AudioClip;
 var moneysystem : MoneySystem ; // for money system
 
 function ApplyDamage (damage : float) {
     // We already have less than 0 hitpoints, maybe we got killed already?
     if (hitPoints <= 0.0)
     {
         return;
     }
 
     hitPoints -= damage;
     //expand enemy search radius if attacked outside default search radius to defend against sniping
     transform.GetComponent(AI).attackRangeAmt = transform.GetComponent(AI).attackRange * 3;
     
     if (hitPoints <= 0.0)
     {
         Detonate();
         //money system
         moneysystem.AddMoney();
 
     }
 }

but same error : NullReferenceException: Object reference not set to an instance of an object

:(

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
0

Answer by Venkat-C · Jun 27, 2013 at 02:34 PM

While you have cast the scriptname, the problem seems to be that you haven't actually told Unity exactly what it is.

Try adding this to your code.

 function Awake () {
 
 scriptName = GameObject.Find("Name_Of_Game_Obj_Where_script_Is_Atached").GetComponent( ScoreTextScript);
 
 }

Then you can call whatever you want to from your other scripts.

Also, if BOTH scripts are attached to the same GameObject, then you can use the SendMessage function.

 SendMessage("AddScore");

More information on SendMessage here http://docs.unity3d.com/Documentation/ScriptReference/GameObject.SendMessage.html

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
0

Answer by Pedras · Mar 28, 2016 at 02:58 PM

Hey! I know its kinda late, but I was searching for the same problem and I found a diferent solution, what you really want to do it's this:

 yourGameObject.GetComponent<TheNameOfTheScript>().yourMethodHere();
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

Null Reference Expantion 1 Answer

Another way to reference scripts? 2 Answers

Save data not creating save file 1 Answer

NullReferenceException 3 Answers

C'# When Taking Variables From Other Scripts, The Values Do Not Update 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