Search Unity

c# I have a drag script that doesnt work on spawned objects!

Discussion in 'Scripting' started by ObstacleGames, Mar 19, 2018.

  1. ObstacleGames

    ObstacleGames

    Joined:
    Nov 3, 2016
    Posts:
    2
    Hi,
    I have a script that allows me to drag the object with my mouse when i hover over it.
    It perfectly works with a normal object in the scene, but when I try to spawn a prefab with the script attached I cant drag it!
    Where is my mistake? Thanks for every answer ;)

    Here is the code:

    Drag Script:
    Code (csharp):
    1.  
    2.     private Vector3 screenPoint;
    3.     private Vector3 offset;
    4.  
    continues here:
    Code (csharp):
    1.  
    2.         void OnMouseDown()
    3.         {
    4.             screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);
    5.  
    6.             offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
    7.  
    8.         }
    9.  
    10.         void OnMouseDrag()
    11.         {
    12.             Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
    13.  
    14.             Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
    15.             transform.position = curPosition;
    16.  
    17.         }
    18.  
    and here is the important section of the spawn script:
    Code (csharp):
    1.  
    2.     void SpawnObject()
    3.     {
    4.         Instantiate(Steak, SteakSpawner.position, SteakSpawner.rotation);
    5.     }
    6.  
     
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,188
    Does your spawned object have a collider? Is it an exact prefab of the object in your scene?
     
  3. ObstacleGames

    ObstacleGames

    Joined:
    Nov 3, 2016
    Posts:
    2
    yes it has a collider and it has the script attached, but it doesnt work
     
  4. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,188
    I mean, if it's an exact copy, then it should work. I would say make sure nothing is blocking it. Add some debug.log messages to your OnMouseDown to see if it's registering, same with the drag.