That looks a bit weird. Where do you execute this code? in
Update? And in what script do you use this code? The AI script itself? What is "
objektnamn" a string? or an object reference?
And finally the most important question: What do you want to achieve?
To me it looks like you do that in the AI script itself but that means that it have to be attached to an object and it adds itself to the object. The new instance you've just added will do the same and add another instance...
If you have new information edit your question and don't post an answer if it's not an answer to the question. You should at least include the function that contains this code snippet and what's the type of your "
Ok, I still can't figure out what's your setup in your scene. You just talk about objects that should be selected. Do they have also an AI script?
Anyways, I guess that will never come to an end. Just some hints:
- You execute either Destroy(GetComponent(AI)) or AddComponent(AI) every frame because you used it in Update(). That means it would add infinite AI Components or will throw endless errors after the last one is deleted.
- The AI script add itself to the gameobject so every new added instance will do the same.
- The Raycast selection code should be there only once. Normally such code is attached to the camera. In your case if you have 3 objects in the scene with the AI script attached all 3 will execute the raycast.
- Your condition
else if(this.gameObject.name == objektnamn.name) is useless since it's just the opposite of
(this.gameObject.name != objektnamn.name). The
else would be enough.
- If you want to activate/deactivate a script you don't need to destroy the script. You just can deactivate it via
Here's an example script that should be attached to the camera which do the selection stuff.
(Note: that's a seperate script. This script can only select objects that have an AI script attached)
var curentSelection : AI = null;
function Update ()
if ( Input.GetMouseButtonDown(1) )
var hit : RaycastHit;
var ray : Ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, hit, 1000.0))
// Try to get the AI script of the new selection
var tempAI : AI = hit.collider.gameObject.GetComponent.<AI>();
// If we selected a new one, deactivate the script.
if (tempAI != null)
// first reactivate the last selected object if there is one
if (curentSelection != null)
curentSelection.enabled = true;
// make the new selected one the current selected.
curentSelection = tempAI;
// deactivate the script
curentSelection.enabled = false;
Mar 15 '11 at 10:49 PM