I want to write a script that is executed in EditMode and if the user presses the mouse button down, a tile is placed. The script is working and it is executed in EditMode, but when I click the script instantiates 2 tiles (One over the other) instad of just one. I dont know what I did wrong. Hope someone can help.`using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
[InitializeOnLoad]
public class TileMapGenerator : MonoBehaviour {
public GameObject currentTile;
public bool isScriptActive;
public List tileList = new List();
TileMapGenerator()
{
SceneView.onSceneGUIDelegate += TileFunction;
}
void TileFunction(SceneView sceneview){
if(isScriptActive == true){
Event e = Event.current;
if(e.type == EventType.MouseDown){
Vector3 position = convertWindowToWorldPoint(e.mousePosition);
switch(e.button){
case 0:
placeTile(position);
break;
case 1:
deleteTile(position);
break;
}
}
}
}
void placeTile(Vector3 position){
int index = tileIndexByCoord(position);
if(index == -1){
Debug.Log("PLACING..."); //This Line is printed always 2 times in the console
GameObject newTile = (GameObject)Instantiate(currentTile, position, Quaternion.identity);
tileList.Add(newTile);
}
}
void deleteTile(Vector3 position){
int index = tileIndexByCoord(position);
if(index != -1){
DestroyImmediate (tileList[index]);
tileList.RemoveAt(index);
}
}
int tileIndexByCoord(Vector3 coordinates){
int i = 0;
foreach(GameObject tile in tileList.ToArray()){
if(tile != null){
if(Vector3.Equals(tile.transform.position, coordinates)){
return i;
}
i++;
}
}
return -1;
}
Vector3 convertWindowToWorldPoint(Vector2 mousePosition){
Ray castRay = HandleUtility.GUIPointToWorldRay(mousePosition);
Vector3 position = castRay.origin;
position.x -= (position.x % 0.29f) - 0.15f; //0.29 is the size of the tile and -0.15 is used to center the tile on the mouse cursor
position.y -= (position.y % 0.29f);
position.z = 0;
return position;
}
}
`