可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I'm working on a "Game" for school, and I need to tally votes. I'm using unity to have characters jump on buttons to count the votes and move on to the next question. This is what I have so far:
using UnityEngine; using System.Collections; public class Vote1 : MonoBehaviour { private int vote1; public GameObject hero_1; void Start () { vote1 = 0; } void Update () { } void OnCollisionEnter2D(Collision2D coll) { if (coll.gameObject.tag == "PlayerObject"){ vote1 = vote1 + 1; print("One Vote Added"); } } }
This should be adding +1 when "hero_1" stands on the button, and displaying the message "One Vote Added" in the console, but that's not what's happening. What am I doing wrong?
Updated The Code
now uses OnCollisionEnter2D, and still doesn't work as intended. What am I missing still?
回答1:
Since print
is a method defined in MonoBehaviour
to print to the Unity console, I'm going to assume that you are in fact looking in the Unity console for the output, and nothing is showing up. That means that either OnTriggerStay
is not getting called, or the collider's root does not have the PlayerObject
tag.
OnTriggerStay
is called when a 3D physics body is inside of a trigger. Make sure that the vote GameObject has the Vote1 component on it, and its collider has "Is Trigger" checked.
Also make sure that the object has a physics body and collider which is not a trigger. The object's root transform (i.e. the one in the hierarchy without any parents) should have the PlayerObject
tag. If the player is inside of a parent container, then transform.root
will get that parent rather than the player itself.
Also, make sure that collisions between the two items are not being filtered out via Edit->Project Settings->Physics->Layer Collision Matrix.
Last, make sure everything is enabled!
Note: You are using OnTriggerStay
which will be hit once per frame while the player is in the trigger. If you don't have some mechanism to remove the player once the vote is cast, then they will be adding 30-60 votes per second, depending on FPS.
回答2:
Assuming that Unity might not support the standard .NET BCL, you might want to look into Unity's console "log" functionality:
enter link description here
Either that or look into a proper logging solution like NLog, for example.
回答3:
Use Console.Write("One vote Added")
if you want to print different strings in the same line in the console. And if you want a new line every time you write to the console, use Console.WriteLine("One Vote Added")
.
回答4:
You might want to use Console.WriteLine("Your message"); Moreover, but i'm not sure, you seem to be getting your transform tag, which is probably not what you intended to do