I'm having a big problem here. I need to know which animator state I'm currently in, in order to make something happen. I've been searching a lot on this matter but because the mecanim animation is so new there isn't much info about it. At least not for unityscript.
Hope someone can help,
Thanks,
RĂ³bert Dan
Unfortunately I don't know JS, but the following C# lines should be easy to be translated.
Animator.GetCurrentAnimatorStateInfo returns an AnimatorStateInfo struct that describes the current animator state.
int stateId = Animator.StringToHash("Base Layer.State Name");
Animator anim = GetComponent<Animator>();
AnimatorStateInfo currentBaseState = anim.GetCurrentAnimatorStateInfo(0);
if (currentBaseState.nameHash == stateId )
{
//you are in stateId
}
Like you see in the example above the animator state's name are hashed (for performance reasons) so you have to hash the name of the state using Animator.StringToHash in order to retrieve the integer id associated with that particular state.
IT'S DO NOT WORK
Try this:
print (currentBaseState.nameHash +" "+ stateId);
And play the animation. They are different
NOVA, I realize your answer was 2 years ago but it matches if you use the "full path" instead of .nameHash.
obl.GetCurrentAnimatorStateInfo (0).fullPathHash == Animator.StringToHash ("Base Layer.StateName")
Related
I need to write a VR application that disables HMD positional tracking for a specific situation and then reenable it again.
In the UI it is a simple as ticking and unticking the TrackedPoseDriver shown in the picture below.
How can I do that via Scripting?
I assume I need to use the enabled property of a game object. But I don't know how to grab a hold of this GameObject (or Component).
EDIT: In case this was clear this is GameObject/Component associated to the main camera.
Ok. So I was able to do It.
What I did is I search MonoBehaviour Based Components on the camera and then cast it to a MonoBehaviour once I found the right one. And then used the enabled property. Like this:
Component[] components = Camera.main.GetComponents(typeof(MonoBehaviour));
bool found = false;
foreach(Component component in components) {
string name = component.ToString();
MonoBehaviour mb = (MonoBehaviour) component;
if (name.Contains(TRACK_POSE_DRIVER_NAME)){
mbTrackingPose = mb;
found = true;
break;
}
}
The unique string that the toString() method provided was somethign like (I don't have it on hand) "Main Camera (Unity.XR.TrackedPoseDriver)". So I just made sure that the string had the "TrackedPoseDriver" and stored that as a MonoBehaviour.
I hope this helps someone else.
I am trying to load an animation from an fbx file and have it play on a GameObject:
TestObject.AddComponent<Animation>();
animation_handler = TestObject.GetComponent<Animation>();
walking_anim = Resources.Load("fbx_anims/walking_anim_test", typeof(AnimationClip)) as AnimationClip;
if(walking_anim == null)
{
Debug.Log("walking anim not found");
}
walking_anim.legacy = true;
animation_handler.AddClip(walking_anim, "walking");
animation_handler.wrapMode = WrapMode.Loop;
In the game loop, I tried using this:
if (Input.GetKeyDown(KeyCode.W))
{
if (!(animation_handler.IsPlaying("walking")))
{
animation_handler.clip = walking_anim;
animation_handler.Play("walking");
}
}
It doesnt give any errors, yet it doesn't work either. Anything I'm missing?
EDIT: For clarification: The model stays in the default T-Pose, after pressing 'W'. After inserting Debug.Logs at different points, I can confirm that the Play function is getting called only once, after which IsPlaying always returns true. Yet the "playing" animation causes no visual changes in the model (yes, the bone names are the same).
You don't want to use the Animation component, it is an old legacy component that has been replaced by the much improved Animator component. There are a lot of good posts on the Internet on how to use it - no need to repeat it here. The important steps are:
Add the Animator (not Animation) component to the model.
Create an "Animator Controller" in your project and add the clips (like the "walking_anim"). Here you can have a lot of different clips and tell Unity how to interpolate between them by using different parameters.
Add the "Animator Controller" to your "Animator" component.
Add an "avatar" of your model (usually created when the model is imported).
By code alter the parameters of the Animator Controller to tell it which animation clips to play.
It may look like a lot of steps, but it is not so hard and you will quickly have a walking, running, jumping creature on your screen. Good luck!
I have a Canvas (World Space Render mode) with a Text and a Button component displayed in a tridimensional space (it's a VR app). The canvas instantiated at runtime using a prefab.
I get a reference to the Text object using:
_codeTextLabel = canvasPrefab.transform.Find("CodeTextLabel").gameObject.GetComponent<Text>();
I want to update the text at run-time using:
void Update()
{
_codeTextLabel.text = _codeText;
}
where _codeText is just a variable I update based on specific events.
The problem is that the Text gets updated only the first time, but if I try to change the variable nothing happens. I have tried several combinations and also the method _codeTextLabel.SetAllDirty() but it doesn't work.
The only way to update the text is to re-instantiate the prefab.
Are you instantiating your prefab before setting the values. If you are storing the _codeTextLabel reference before instantiating then your reference will point to the prefab not the runtime object. I can't see the rest of your code, so I can't say for sure. (I would have asked as a comment, but as I'm new I don't have the reputation to do so)
edit: I did a test to try and recreate your problem. I made the following script and it appears to work as expected. CanvasPrefab is a worldspace canvas with a UnityEngine.UI.Text component attached. (The script is attached on an empty game object in the scene btw)
public class ChangeText : MonoBehaviour
{
public GameObject CanvasPrefab;
private GameObject runtimeCanvas;
public string runtimeText = "something";
private Text textRef;
// Start is called before the first frame update
void Start()
{
runtimeCanvas = GameObject.Instantiate(CanvasPrefab);
textRef = runtimeCanvas.GetComponentInChildren<Text>();
}
// Update is called once per frame
void Update()
{
textRef.text = runtimeText;
}
}
as long as you did something wrong, It works absolutely so I guess there are several cases
Failed to do "_codeTextLabel = canvasPrefab.transform.Find("CodeTextLabel").gameObject.GetComponent();"
'_codeTextLabel' lost reference from 'GameObject.
Doesn't change runtimeText' change at all
Subscription of events failed I mean, your updating scripts doesn't get proper event to update that text.
Without codes, this is only thing I can guess for yours so please check above I hope there is case among above.
I'm not yet as much into Java as I'd like to be, so I find my current task to be quite a bit challenging:
A chart showing data gathered in another class.
A slider whose end value is determined by the last entry of in the dataset used in the chart.
The playbutton currently doesn't do anything except letting the slider tick in steps of 5 until it is paused again.
My problem right now is: I am supposed to highlight one item at a time in the chart based on which value the slider currently shows.
And to be honest... I'm not yet used to renderers yet.
If I understood it correctly I would need to use
renderer.drawItem(java.awt.Graphics2D g2,
XYItemRendererState state,
java.awt.geom.Rectangle2D dataArea,
PlotRenderingInfo info,
XYPlot plot,
ValueAxis domainAxis,
ValueAxis rangeAxis,
XYDataset dataset,
int series,
int item,
CrosshairState crosshairState,
int pass)
but I am totally inexperienced with as well the method as its arguments and got no idea how to initialize them.
I mean... I got a plot, a dataset, and 2 series from the chart, I also suggest "item" would be the index of the item to highlight in the series, which I could convert from the slider-value.
Unfortunately plaguing google about it turned out to be rather frustrating since all I got was the very code I posted above on about 50 different pages (I gave up after).
I would like to know ... first of all if I am even about to use the correct method and, as ashamed as I am to ask like this... how to use it.
Well... looking forward to some answers and... thanks in advance.
Well, I now solved my problem in a different way than I intended to but it works out just fine for me.
Instead of highlighting a point in the curves I just simply add a Domainmarker that would adjust based on the value the slider currently shows.
class1 TestSlider
private HashSet<SliderListener> sliderListenerSet = new HashSet<SliderListener>();
public void addSliderListener(SliderListener Listener){
sliderListenerSet.add(Listener);
}
slider.addChangeListener(this);
public void stateChanged(ChangeEvent e) {
// TODO Auto-generated method stub
JSlider source = (JSlider)e.getSource();
if (!source.getValueIsAdjusting()) {
fireSliderChanged();
}
}
public void fireSliderChanged(){
for (SliderListener currentListener : sliderListenerSet)
currentListener.sliderValueChanged();
}
class2 SliderListener
public interface SliderListener extends EventListener{
public void SliderValueChanged();
}
class3 Chart
Marker marker = new ValueMarker(0);
plot.addDomainMarker(marker); //so that it would be there at the beginning
TestSlider ts = new TestSlider();
ts.addSliderListener(new SliderListener(){
#Override
public void sliderValueChanged() {
plot.removeDomainMarker(marker); //I only want one of them at a time - the one with the value the slider is currently showing so remove the old one...
marker = new ValueMarker(ts.slider.getValue());
plot.addDomainMarker(marker); // ... and add the one with the new value
}
});
}
I tried to keep it as short and universal as I could and I hope I didnt cut out anything important.
Well, I'm still new to this site, so... in case I did a mistake somewhere feel free to tell me.
Is it possible to remove a part of a name given to a GameObject? For instance:
Im instantiating gameobjects for the use of bullets. I give them the name of the player shooting the bullet. So if a player's name is "Ben", his bullets are called Ben's bullet.
gameObject.name = playerName + "'s bullet";
Now I'm trying to use this name to know wich person gives the finishing blow to an other player. And to do this I want find the player object with the same name as the bullet, and update his kill count. So I want to remove the "'s bullet" part from the bullets name.
So long story short: Is it possible to remove a part of a name given to a GameObject?
Hope that this is clear enough en help is really appreciated. Thanks in advance!
Edit: This is the part where the name has to change:
if(other.gameObject.tag == "bullet"){
var colBullet = other.transform.name;
playerHealth = playerHealth - 5;
if(playerHealth <= 0){
onDie();
//colBullet = colBullet - "'s bullet";
GameObject.Find(colBullet);
} }
The name of the collided object is put in the colBullet variable. I printed it and it says: Playername's bullet. This works but now the only thing it needs is the 's bullet being removed
int suffixLength = "'s bullet".Length;
string player = gameObject.name.Substring(0, gameObject.name.Length - suffixLength);
But maybe it would be better to have a property that doesn't need manipulating to find the player name?
Long story short: keep a reference to the player in your GameObject, instead of its name. This way you save on look ups for the player if you want to, for example, increase the experience or gold the shooter has for each kill. For stray bullets, or recycled ones, just set Player to null.