Search code examples
c#unity-game-enginemousetransformscale

game in Unity3d scaling objects with mouse in c sharp


I'm making a game in unity3d in C#

I would like to be able to make an object smaller by clicking on it with the left mouse button and bigger with right mouse button. The problems with this code are: 1. it doesn't allow to scale down unless its been scaled up 2. if there are multiple objs, they all get affected once they've been clicked on. I've tried a few different ways to do it and I'm guessing it's something to do with the resize bool. Your help is much appreciated

using UnityEngine;
using System.Collections;

public class Scale : MonoBehaviour 
{
    public GameObject obj;

    private float targetScale;
    public float maxScale = 10.0f;
    public float minScale = 2.0f;

    public float shrinkSpeed = 1.0f;

    private bool resizing = false;


void OnMouseDown()
    {
        resizing = true;

    }

    void Update()
    {
        if (resizing)
        {
             if (Input.GetMouseButtonDown(1)) 
            {
                targetScale = maxScale;


            }
             if (Input.GetMouseButtonDown(0))
            {
                targetScale = minScale;


            }

            obj.transform.localScale = Vector3.Lerp(obj.transform.localScale, new Vector3(targetScale, targetScale, targetScale), Time.deltaTime*shrinkSpeed);

            Debug.Log(obj.transform.localScale);

            if (obj.transform.localScale.x == targetScale)
            {
            resizing = false;
                Debug.Log(resizing);
            }
    }
    }
}

Solution

  • using UnityEngine; using System.Collections;

    public class Scale : MonoBehaviour {

    public float maxScale = 10.0f;
    public float minScale = 2.0f;
    public float shrinkSpeed = 1.0f;   
    
    private float targetScale;
    private Vector3 v3Scale;
    
    void Start() {
       v3Scale = transform.localScale;   
    }
    
    void Update()
    {
       RaycastHit hit;
       Ray ray;
    
       if (Input.GetMouseButtonDown (0)) {
         ray = Camera.main.ScreenPointToRay(Input.mousePosition);
         if (Physics.Raycast(ray, out hit) && hit.transform == transform) {
          targetScale = minScale;
          v3Scale = new Vector3(targetScale, targetScale, targetScale);
         }
    
       }
    
       if (Input.GetMouseButtonDown (1)) {
         ray = Camera.main.ScreenPointToRay(Input.mousePosition);
         if (Physics.Raycast(ray, out hit) && hit.transform == transform) {
          targetScale = maxScale;
          v3Scale = new Vector3(targetScale, targetScale, targetScale);
         }
       }
    
       transform.localScale = Vector3.Lerp(transform.localScale, v3Scale, Time.deltaTime*shrinkSpeed);
    }
    

    }