My "game" read a file XML, identify some elements and instance him at runtime. This instances is of a prefab.
So, I have a loop with a variable "ins" that create the instances:
ins = (GameObject)Instantiate (this.MyPrefab, position, Quaternion.identity);
I would like, for example, to click on a instance and change its color and not on all instances.
The problem in your code is thatUpdate() calls Click() in every frame. So, whenever you press the mouse button if( Input.GetMouseButtonDown(0) ) becomes true for every prefab and they all process the click event, irrespective of whether they were clicked on or not.
The solution would be to add a Collider component to your prefab and implement OnMouseDown() in ButtonDiagram class to detect mouse clicks on the object. Something like :
public class ButtonDiagram : MonoBehaviour
{
// rest of your code
void OnMouseDown()
{
Debug.Log("Click!");
}
}
Unity's documentation:
http://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseDown.html
You could do an array of gameobjects.
Do a foreach loop and add each instance to the your array. Then you could do ins[0].DOSOMETHING or, simpler, have the prefabs you're instantiating have a script on it then accepts mouse clicks or other input and that will affect only the gameobject/prefab that the user interacts with.
using UnityEngine;
using System.Collections;
public class Program : MonoBehaviour
{
private Diagram diagram { get; set; }
public string arquivoXMI;
public GameObject ButtonDiagramGameObject;
private const int SPACEX = 2;
private GameObject ins;
public ArrayList instances{ get; private set; }
// Use this for initialization
void Start ()
{
this.diagram = new Diagram (arquivoXMI);
ButtonForEachSequenceDiagram ();
}
//BUTTON FOR EACH SEQUENCE DIAGRAM
private void ButtonForEachSequenceDiagram()
{
instances = new ArrayList ();
if (this.diagram.SequenceDiagrams.Count > 0) {
float increment = (this.ButtonDiagramGameObject.transform.localScale.x / 2) + SPACEX;
float position = 0;
foreach( Sequence s in this.diagram.SequenceDiagrams )
{
float posBDx = position;
float posBDy = this.ButtonDiagramGameObject.transform.position.y;
float posBDz = this.ButtonDiagramGameObject.transform.position.z;
Vector3 posButtonDiagram = new Vector3 (posBDx, posBDy, posBDz);
ins = (GameObject)Instantiate (this.ButtonDiagramGameObject, posButtonDiagram, Quaternion.identity) ;
ins.GetComponentInChildren<ButtonDiagram> ().NameDiagram ( s.Name );
instances.Add(ins);
position += increment;
}
}
}
// Update is called once per frame
void Update ()
{
foreach( GameObject i in instances ){
i.GetComponentInChildren<ButtonDiagram>().Click();
}
}
}
using UnityEngine;
using System.Collections;
public class ButtonDiagram : MonoBehaviour {
public TextMesh Name;
public GameObject MyCube;
private string nameDiagram;
private float random;
// Use this for initialization
void Start () {
// random = Random.Range(-10.0f, 10.0f);
// NameDiagram = random.ToString();
Name.text = nameDiagram;
}
public void NameDiagram( string nome ){
this.nameDiagram = nome;
}
public void Click(){
if( Input.GetMouseButtonDown(0) )
{
Debug.Log("Click!");
}
}
// Update is called once per frame
void Update () {
}
}
Related
I'm currently making a simple game for my project, which is spawning food and damaging it until its vanishes. I have to write a script that instantiates a random object from an array, attaches the script to it, and damages the instantiated food in another script. The current problem now is Unity telling me that I have a Null Reference Exception on both scripts, I tried to fix it by attaching the script to the instantiated object, but still, the problem remains.
Here the code on the script that attaches to the instantiated object, and also spawning the object too:
`
public class Food : MonoBehaviour
{
public GameObject[] food;
public Vector3Int spawnPosition;
public int health = 200;
public int currentHealth;
private GameObject clone;
public void Start()
{
currentHealth = health;
SpawnFood();
}
//Spawning food
public void SpawnFood()
{
int random = Random.Range(0, food.Length); //Null Reference Exception happen in this line.
clone = Instantiate(food[random], this.spawnPosition, Quaternion.identity) as GameObject;
clone.AddComponent<Food>();
}
public void TakeDamage(int damage)
{
currentHealth -= damage;
//play hurt effect
if(currentHealth < 0)
{
Vanish();
}
}
void Vanish()
{
Debug.Log("Vanished");
}
}
`
Here is the other script:
`
public class Board : MonoBehaviour
{
public Tilemap tilemap { get; private set; }
public Piece activePiece { get; private set; }
public TetrominoData[] tetrominoes;
public Vector3Int spawnPosition;
public Vector2Int boardSize = new Vector2Int(10, 20);
public int damage;
public Food clone;
public TextMeshProUGUI hud_score;
public static int currentScore = 0;
public int scoreOneLine = 40;
public int scoreTwoLine = 100;
public int scoreThreeLine = 300;
public int scoreFourLine = 1200;
private int numberOfRowsThisTurn = 0;
public RectInt Bounds
{
get
{
Vector2Int position = new Vector2Int(-this.boardSize.x / 2, -this.boardSize.y / 2);
return new RectInt(position, this.boardSize);
}
}
private void Awake()
{
this.tilemap = GetComponentInChildren<Tilemap>();
this.activePiece = GetComponentInChildren<Piece>();
//call Tetromino.Initialize() to spawn pieces
for (int i = 0; i < this.tetrominoes.Length; i++)
{
this.tetrominoes[i].Initialize();
}
}
private void Start()
{
SpawnPiece();
}
private void Update()
{
UpdateScore();
UpdateUI();
}
public void UpdateUI()
{
hud_score.text = currentScore.ToString();
}
public void UpdateScore()
{
if(numberOfRowsThisTurn > 0)
{
if(numberOfRowsThisTurn == 1)
{
ClearedOneLine();
}
else if (numberOfRowsThisTurn == 2)
{
ClearedTwoLine();
}
else if (numberOfRowsThisTurn == 3)
{
ClearedThreeLine();
}
else if (numberOfRowsThisTurn == 4)
{
ClearedFourLine();
}
numberOfRowsThisTurn = 0;
}
}
public void ClearedOneLine()
{
currentScore += scoreOneLine;
clone.GetComponent<Food>().TakeDamage(10); //Null Reference Exception happen in this line.
}
public void ClearedTwoLine()
{
currentScore += scoreTwoLine;
clone.GetComponent<Food>().TakeDamage(20); //Null Reference Exception happen in this line.
}
public void ClearedThreeLine()
{
currentScore += scoreThreeLine;
clone.GetComponent<Food>().TakeDamage(40); //Null Reference Exception happen in this line.
}
public void ClearedFourLine()
{
currentScore += scoreFourLine;
clone.GetComponent<Food>().TakeDamage(80); //Null Reference Exception happen in this line.
}
`
Please help and thank you for the help.
Here is the Inspector image with 64 elements in an array:
I have tried to attach the script to the instantiated object when that object is being spawned.
I don't see food set anywhere. You need to populate the array inside Food from the Inspector or at least, populate programmatically in Food.Start() before using it.
Can you also show us a printscr of the Inspector view where Food is attached as component? The main focus here is the food array.
the food array is empty it should be filled by you,
instantiate doesn't fill it, it takes an object from the array and spawn it.
fill it with prefabs of foods that already has the food component no need to add it in code
I'm making an inventory system and want to use a button to move all items from under the button to a grid (which is their original transform coordinates). want to reference the coordinate to the original game object through their index, but it does not move at all. I'm not sure if the lists I have set up have nothing indexed, or the translation isn't working. what can I correct here to make this work?
public class BaseInventory : MonoBehaviour
{
public List<GameObject> myObjects;
public Vector3 rootV3;
public float delayBetweenObjects = .1f;
public float animationDuration = .1f;
public List<Vector3> baseV3 = new List<Vector3>();
public Vector3 endV3;
void SavePositions()
{
foreach(GameObject g in myObjects)
{
baseV3.Add(g.transform.position);
}
}
private void Awake()
{
Hide();
}
private void Hide()
{
foreach (GameObject g in myObjects)
{
g.SetActive(false);
}
}
public void ShowItems()
{
StartCoroutine(Show());
}
IEnumerator Show()
{
foreach (GameObject g in myObjects)
{
int i = myObjects.IndexOf(g);
endV3 = baseV3[i];
yield return new WaitForSeconds(delayBetweenObjects);
g.SetActive(true);
g.transform.DOMove(endV3, animationDuration).From();
}
}
}
I can't seem to get this to work.
The player presses 1 or 2 or 3 etc depending where the weapon is on the hotbar and it will show the weapon by setting it active in the hierarchy.
everything works fine client side obviously but I cannot get it to show from the other players perspective. Not sure where to put the photon view or where to put the code exactly but this is my code that is currently on the hotbar slot.
Also worth mentioning that the item is selected from an actual inventory and not just a simple switch so it all corresponds to another bit of code that is the item script attached to the pickupable item.
Thanks if advanced if anyone can point me in the right direction.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using Hashtable = ExitGames.Client.Photon.Hashtable;
using Photon.Realtime;
public class HotbarSlot : MonoBehaviourPunCallbacks
{
public GameObject[] unstaticItems;
public static GameObject[] items;
public Inventory inv;
public NewPlayerHealth updateVitals;
public AudioSource audioSource;
public AudioClip Eating;
public KeyCode key;
public PhotonView PV;
[SerializeField]
private GameObject placeableObjectPrefab;
[SerializeField]
private GameObject currentPlaceableObject;
private float mouseWheelRotation;
void Awake()
{
PV = GetComponent<PhotonView>();
}
void Start()
{
if (unstaticItems.Length > 0)
items = unstaticItems;
audioSource = GetComponent<AudioSource>();
}
void Update()
{
if (!PV.IsMine) return;
if (Input.GetKeyDown(key))
Equip();
if (Input.GetKeyDown(key))
{
EatFood();
}
PlaceFurnace();
RotateFromMouseWheel();
}
void Equip()
{
{
photonView.RPC("EquipRPC", RpcTarget.AllBuffered);
}
}
[PunRPC]
void EquipRPC()
{
{
if (transform.childCount > 1)
{
Item item = transform.GetChild(1).GetComponent<Item>();
if (item.equipmentType == "Hand")
{
for (int i = 0; i < items.Length; i++)
{
if (i == item.equipmentIndex)
{
items[i].SetActive(!items[i].activeInHierarchy);
}
else
{
items[i].SetActive(false);
}
}
}
}
}
}
Im trying to do a property drawer for a class that i need to be updated as well as editable from the editor.
If i make the class a monobehaviour the serialisation stops working, but if i remove the monobehaviour inheritance it wont update with the game loop.
Is there any way to have both? I would need the object to be able to instantiate with default (empty) values if a monobehaviour script has non instantiated reference.
[Serializable]
public class MySmallTestProp : MonoBehaviour, ISerializationCallbackReceiver
{
[SerializeField]
private string name;
[SerializeField]
private string _name;
[SerializeField]
private float _someFloat;
public float someFloat;
public MySmallTestProp()
{ }
public void OnBeforeSerialize()
{
_name = name;
}
public void OnAfterDeserialize()
{
name = _name;
}
}
[CustomPropertyDrawer(typeof(MySmallTestProp))]
public class MySmallTestPropPropertyDrawer : PropertyDrawer
{
float rowHeight;
int rowSpacing = 5;
int index;
Rect currentPosition;
public override float GetPropertyHeight(SerializedProperty prop, GUIContent label)
{
rowHeight = base.GetPropertyHeight(prop, label);
var rows = 2;
if (Application.isPlaying)
{
rows++;
}
else
{
rows++;
}
return rowHeight * rows;
}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
index = 1;
currentPosition = position;
EditorGUI.BeginProperty(position, label, property);
var nameProp = property.FindPropertyRelative("_name");
EditorGUI.PropertyField(NextPosition(), nameProp, new GUIContent("Name"));
EditorGUI.EndProperty();
}
Rect NextPosition()
{
currentPosition.height = rowHeight;
currentPosition.y = rowSpacing + (rowHeight + rowSpacing) * index++;
return currentPosition;
}
}
So if I understand you correctly what you want to achieve is having a class which is
Serializable
has some default field values
Receives an Update call every frame
Actually I don't think you need any custom property drawer for this.
First two points are as simple as having e.g.
[Serializable]
public class Example
{
// By default this has the value "Default String"
public string someString = "Default String";
// This can be edited only via the Inspector
// by default it is 42
[SerializeField] private float someFloat = 42.0f;
// This is a read-only public access
public float SomeFloat => someFloat;
}
Now to the last and tricky part - the update calls.
The easiest way is to have a dedicated MonoBehaviour like e.g.
public class UpdateDispatcher : MonoBehaviour
{
// Storing the instance for Singleton Pattern
private static UpdateDispatcher _instance;
// Register to this event to receive one call each Update
public static event Action OnUpdate;
// This method is automatically called by Unity when the application is started
// or you enter play mode in the editor
[RuntimeInitializeOnLoadMethod]
private static void Init()
{
// _instsnce is already assigned and alive?
if(_instance) return;
// Otherwise search for one in the scene
_instance = FindObjectOfType<UpdateDispatcher>();
// Found one?
if(_instance) return;
// Otherwise create it now
_instance = new GameObject(nameof(UpdateDispatcher)).AddComponent<UpdateDispatcher>();
}
private void Awake ()
{
// Does another instance already exist?
if(_instance && _instance != this)
{
// Destroy this one
Destroy (gameObject);
return;
}
// Otherwise assign this as the instance and make sure it isn't destroyed when the scene chsnges
_instance = this;
DontDestroyOnLoad (gameObject);
}
private void Update ()
{
// Call the event every frame if something is registered
OnUpdate?.Invoke ();
}
}
And then you can use ISerislizationCallbackReceiver but not for actually doing the serialization (it is already done automatically for the fields) but rather for registration to the update callback like e.g.
[Serializable]
public class Example, ISerializationCallbackReceiver
{
// By default this has the value "Default String"
public string someString = "Default String";
// This can be edited only vis the Inspector
// by default it is 42
[SerializeField] private float someFloat = 42.0f;
// This is a read-only public access
public float SomeFloat => someFloat;
// Nothing to do here, only needed for the interface
public void OnBeforeSerialize() { }
public void OnAfterDeserialize()
{
// Register to the Update event
// It is save to unregister before registering even if we haven't been registered before
// this makes sure we are registered only exactly once
UpdateDispatcher.OnUpdate -= Update;
UpdateDispatcher.OnUpdate += Update;
}
private void Update ()
{
someFloat += Time.deltaTime;
}
}
This answer should be more like a comment, but due to the extension I've decided to post it here.
The objective of a PropertyDrawer is to display properties differently on the editor.
To achieve that you need 2 things:
1.One class that inherits from PropertyAttribute, this will be the reference used in your future scripts.
2.Another class that inherits from PropertyDrawer, here you can type HOW to display the attribute.
One implementation example of a property drawer that shows an attribute without leting the user to edit it from editor:
using UnityEditor;
using UnityEngine;
public class DisplayWithoutEdit : PropertyAttribute
{
}
[CustomPropertyDrawer(typeof(DisplayWithoutEdit))]
public class DisplayWithoutEditDrawer : PropertyDrawer
{
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
return EditorGUI.GetPropertyHeight(property, label, true);
}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
GUI.enabled = false;
EditorGUI.PropertyField(position, property, label, true);
GUI.enabled = true;
}
}
Then you can use it on another script doing something like:
[DisplayWithoutEdit] public float randomNumber = 0f;
When I press Space, the player and the dummy are supposed to swap places. This doesn't just happen once, it needs to happen everytime I press the Space bar so they can swap back and forth. However, sometimes it works and sometimes it doesn't. When it doesn't work, the dummy teleports to the player and then the player teleports inside of the dummy (as that is where its last position is). This just kind of pushes the player about.
Here is the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerSwap : MonoBehaviour
{
public GameObject player;
public GameObject dummy;
public GameObject cameraAnchor;
public Transform playerLastPos;
public Transform dummyLastPos;
public bool haveSwapped;
public bool canSwap;
public float swapRadius;
public LayerMask dummyInRadius;
// Update is called once per frame
void Update()
{
canSwap = Physics.CheckSphere(player.transform.position, swapRadius, dummyInRadius);
SwapTransforms();
if (canSwap)
{
if (Input.GetKeyDown(KeyCode.Space))
{
haveSwapped = !haveSwapped;
Swapping();
}
}
else
{
Debug.Log("Can't Swap");
}
cameraAnchor.transform.position = player.transform.position;
}
public void SwapTransforms()
{
if (haveSwapped)
{
dummyLastPos.position = player.transform.position;
playerLastPos.position = dummy.transform.position;
}
else
{
dummyLastPos.position = dummy.transform.position;
playerLastPos.position = player.transform.position;
}
}
public void Swapping()
{
if (haveSwapped)
{
player.transform.position = dummyLastPos.position;
dummy.transform.position = playerLastPos.position;
}
else
{
player.transform.position = playerLastPos.position;
dummy.transform.position = dummyLastPos.position;
}
}
public void OnDrawGizmos()
{
Gizmos.color = Color.white;
Gizmos.DrawWireSphere(player.transform.position, swapRadius);
}
}
I've solved it. After cleaning up most of the code and realsing I had to turn off movement and the character controller on the player (Link:Unity Answers), I came up with this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerSwap : MonoBehaviour
{
public ThirdPersonMovement playerMove;
public GameObject player;
public GameObject dummy;
public GameObject cameraAnchor;
public Transform playerLastPos;
public Transform dummyLastPos;
public bool canSwap;
public float swapRadius;
public LayerMask dummyInRadius;
// Update is called once per frame
void Update()
{
canSwap = Physics.CheckSphere(player.transform.position, swapRadius, dummyInRadius);
if (canSwap)
{
if (Input.GetKeyDown(KeyCode.Space))
{
playerMove.canMove = false;
player.GetComponent<CharacterController>().enabled = false;
SetTransforms();
}
}
else
{
Debug.Log("Can't Swap");
}
cameraAnchor.transform.position = player.transform.position;
}
public void SetTransforms()
{
dummyLastPos.position = dummy.transform.position;
playerLastPos.position = player.transform.position;
Debug.Log("Set Transforms");
Swapping();
}
public void Swapping()
{
player.transform.position = dummyLastPos.position;
dummy.transform.position = playerLastPos.position;
dummy.transform.rotation = player.transform.rotation;
Debug.Log("Swap");
playerMove.canMove = true;
player.GetComponent<CharacterController>().enabled = true;
}
public void OnDrawGizmos()
{
Gizmos.color = Color.white;
Gizmos.DrawWireSphere(player.transform.position, swapRadius);
}
}