Counter problem

Hi. I am a beginner in Unity. I am doing the Challenge 03 (Unity 3D Student - 3d Modelling) and got some problems. I have written a script.

var Counter :int =0;
function Update(){
var fwd =transform.forward*100;
rigidbody.AddForce(fwd);
}
function OnCollisionEnter(theCollision:Collision){
if (theCollision.gameObject.name=="smalltarget" ){
Destroy(theCollision.gameObject);
Destroy(gameObject);
   //not Destroy(gameObject.Find("smalltarget");
   Counter++;
   //tried also Counter+=1

Debug.Log("smalltarget destroyed");
}
Debug.Log(Counter);
if (Counter >=3){
Debug.Log("now scene must be loaded");
}
}

The problem is that the Counter number remains 1 in Debug.Log and it is not rising. What should I do? Could you help me please?

1 Answer

1
  • What is the Log printing out?
  • Which GameObject/prefab is this script attached to?
  • Line 9: Destroy(gameObject); seems to be destroying the current object and by extension this instance of the script, if any other instances of this script exist on other gameObjects in your scene they will have their own counter variable, that will hold independent values.

OK then: Your counter is an instance variable, i.e. each instance has it's own independent counter initialized to 0, that is why it never seems to get past 1. Try changing line 1 to: static var Counter :int = 0; then running your game. If you are then getting errors accessing Counter on lines 11, 16 & 17 you should adopt the ClassName.variableName format. A quick write up and example is available [here][1]. [1]: http://wiki.unity3d.com/index.php?title=UnityScript_Keywords#static

–

Making that variable static worked. Thanks. But I can't understand what means static? so...so far I understand trough : Class-a collection of fuctions. still What is an instance variable? What is a static variable? An instance of a class is actually an element of that class? so example transform=class translate=instance of that class? Look.At()=other instance? I am a little puzzled. I have never studied JavaScript before this PDF(http://download.unity3d.com/support/Tutorials/2%20-%20Scripting%20Tutorial.pdf ) and Unity Student tutorials... only brief Pascal.

–

Found this site http://math.hws.edu/eck/cs124/javanotes6/contents-with-subsections.html Should I read all contents until chapter 5?

–

Yes...thank you...but that book seems to be extremely time consuming. 200 pages for Faculty in an year would take me 3 years. Do you know a javascript book that uses these notions dirrectly inside Unity? (I am searching for a better explanation of the 3 notions listed above).

–

OK, I did a little more digging and found this tutorial on static variables. ([1]) This is using console applications in Java for examples, but the code is very readable so it should be no problem. [1]: http://www.caveofprogramming.com/frontpage/articles/java/java-for-beginners-static-variables-what-are-they/

–