- Home /
Multiple object with same script
Hi all, new here and I have small problem that I cannot solve. I tried to read the forum and couldn't find solution that will help me. Anyway to the point:
I have a script attached to object. to move the object. All good. but when I add another object, they are moving together. I tried to debug and saw that line 34 was executed twice (2 object on the display) So I was thinking can it be because of the Raycast detection in same script?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class moveBlock : MonoBehaviour
{
private RaycastHit hit; //Detect side of block that was presssed
private Vector3 mousePos; //Mouse position on the collision
private string hitName ; //Collider name
private Vector2 origPos, targetPos; //Initioate original and target positions
private float timeToMove = 0.2f; //Time that will take to move the block
private bool isMoving; //Is the block moving
// Update is called once per frame
void Update()
{
mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
if (Physics.Raycast(mousePos, Vector3.forward, out hit, 100.0f))
{
hitName = hit.collider.name; //Write the name of the collider that was hit
}
else
{
hitName = "none"; //If no collision accured, none.
}
//set if velocity is not zero, isMoving = true;
if (Input.GetMouseButtonDown(0) && !isMoving)
{
switch (hitName)
{
case "r":
StartCoroutine(MoveBlock(Vector2.right / 2));
break;
case "l":
StartCoroutine(MoveBlock(Vector2.left / 2));
break;
case "u":
StartCoroutine(MoveBlock(Vector2.up / 2));
break;
case "d":
StartCoroutine(MoveBlock(Vector2.down / 2));
break;
default:
break;
}
}
}
private IEnumerator MoveBlock (Vector2 direction)
{
isMoving = true;
float elapsedTime = 0;
origPos = transform.position;
targetPos = origPos + direction;
while(elapsedTime<timeToMove)
{
transform.position = Vector2.Lerp(origPos, targetPos, (elapsedTime / timeToMove));
elapsedTime += Time.deltaTime;
yield return null;
}
transform.position = targetPos;
isMoving = false;
}
}
Any idea where can I find good explanation or maybe someone have a explanation? Thanks in advance.
Answer by logicandchaos · Jan 20, 2021 at 03:27 PM
The move together because they have the same script on them. To make them move differently you will need to write a new script. Line 34 is called twice, once for each object. When case are is triggered for object 1 it is also triggered for object 2. How do you want the second object to move?
I don't want it to move until I click on it.
So I started to write 2 different scripts already.
One will detect a click on the block. Specific side of the block (to what side to move) and also will get name of specific block.
the other script will move block (it will get name of the block and to what side it will move)
Think I will connect both scripts to $$anonymous$$ain camera? Or is there any other way around. $$anonymous$$aybe more proper?