Game Objects not using same script independently.
Hello, I am trying to use the same script on multiple game objects that will allow me to grab and move the game object around. The problem is that as soon as I click on one object all other objects move their positions to the position of my cursor.
Here is a portion of the script that controls the movement.
public class Pet : MonoBehaviour {
private bool canGrab, grabbed;
private static Pet selectedPet;
public Pet (string name, Vector3 info, Vector2 scale) {
this.maxHealth = info.x;
this.maxEnergy = info.y;
this.maxHunger = info.z;
this.petName = name;
this.minScale = scale.x;
this.maxScale = scale.y - minScale;
this.health = maxHealth;
this.hunger = maxHunger;
this.energy = maxEnergy;
}
private void updatePhysics () {
if (this.isGrabbed ()) {
selectedPet = this;
gameObject.transform.position = Camera.main.ScreenToWorldPoint (Input.mousePosition);
gameObject.transform.position = new Vector3 (gameObject.transform.position.x, gameObject.transform.position.y, -0.2F);
if (gameObject.transform.position.y < this.groundLevel) {
gameObject.transform.position = new Vector3 (gameObject.transform.position.x, groundLevel, -0.2F);
}
this.GetComponent <Rigidbody2D> ().gravityScale = 0;
}
}
private void updateRaycast () {
//Register mouse input for desktop
RaycastHit2D hit = Physics2D.Raycast (Camera.main.ScreenToWorldPoint (Input.mousePosition), Vector2.zero);
if (hit.collider != null && !Input.GetMouseButton (0)) {
if (hit.collider.tag == "Pet") {
this.canGrab = true;
} else {
this.canGrab = false;
}
}
if (hit.collider == null) {
this.canGrab = false;
}
}
protected void updateBase () {
//Check if grabbed//
if (Input.GetMouseButton (0)) {
if (this.canGrab) {
this.grabbed = true;
}
} else {
this.grabbed = false;
gameObject.GetComponent <Rigidbody2D> ().gravityScale = 1;
}
}
}
Here is the script that is link to the prefab.
public class Pet_Penguin : Pet {
public Pet_Penguin () : base ("Ping", new Vector3 (100, 100, 100), new Vector2 (0.4F, 1.2F)) {
}
void Update () {
updateBase ();
}
}
Answer by tormentoarmagedoom · Aug 13, 2018 at 07:54 PM
Good day.
Dont make the variable selectedPet static, make it just public.
Bye!
The selectedPet is static because it creates a little box with info about the pet. It has nothing to do with grabbing or moving the animal.
Your answer
Follow this Question
Related Questions
how to move a gameobject based on a dice roll 1 Answer
New Vector2 won't take effect when called from another script in the same GameObject. 0 Answers
How to get scripts to detect foreign variable change? 0 Answers
How can I stop a gameobject movement with timer? 0 Answers
Moving on the XZ plane 0 Answers