Character Controller speed: running vs. walking - animation

I imported the standard characters package into a fresh Unity project, and then dragged a 3rd person character controller prefab and dropped it into the scene.
However, I cannot seem to figure out which variable to modify to get the avatar to walk!
I keep changing the speed-related settings, but the character always seems to be running when I press the key W.
I would appreciate some help to get me started in this...

I created example code for you. You can see how It works and set its own. If you show your character controller codes I try to be more help.
There is two step;
1. Set your character animation controller like this.
Call animation from your character controller script like this.
using UnityEngine;
using System.Collections;
public class Test : MonoBehaviour
{
private Animator anim;
float yourSpeed;
void Awake ()
{
anim = GetComponent<Animator> ();
}
void Update ()
{
if (Input.GetKeyDown (KeyCode.W) && yourSpeed > 100f)
{ //I dont know how works your speed.
anim.SetTrigger ("RunAnim");
}
else if (Input.GetKeyDown (KeyCode.W))
{
anim.SetTrigger ("WalkAnim");
}
else
{
anim.SetTrigger("IdleAnim");
}
}
}
Also you can watch official unity tutorial.

Related

Unity UI Onclick inspector with Enumeration

I have a question.
Here's My inspector Window.
In case of On Click() window, I'd like to set parameter that is type of Enum.
not string or int.
In other words, I'd like to use
void GoToNext(DATA_TYPE type).
But that doesn't show up.
Even if I set my enum as [SerializedField], that doesn't show in this window.
How can I do this?
I found a great solution to this from the user 'TobiLaForge' on this Unity forum. At least it is the best solution worked for me where I had only a few enums to handle.
1) Declare your enum outside of your class you use it in or create it anywhere else outside of a MonoBehaviour.
2) Create a script, attach it to your button:
using UnityEngine;
public class GetEnum : MonoBehaviour{
public MyEnum state;
}
3 Add this or change your orginial function where you use the enum
public void GetEnumState(GetEnum g)
{ if(g.state == MyEnum.something)
DoSomething();
}
4) In the OnClick() function slot select your function and drag the GetEnum script into the slot.
This will need a new MonoBehaviour script for each enum you use in that way. Here is my inspector after.
You can't currently do this, Unity doesn't support it. But, since enums are basically ints, perhaps you could setup your function to accept an int and somehow cast it to the appropriate enum?
I tried this little experiment in some code I have with an enum, and it seemed to work fine:
public enum unitType {orc_warrior, archer, none};
int test2 = 0;
unitType test;
test = (unitType)test2;
Debug.Log(test);
test2 = 1;
test = (unitType)test2;
Debug.Log(test);
Debug correctly printed out orc_warrior and then archer
To make clear how it works what nipunasudha suggest, here the full code example how I use it. Please notice the need of ´SerializeReference´ instad of ´SerializeField´ otherwise all your buttons would end with the same state - which is usually not what you want to achieve.
using UnityEngine;
public class MenuInvoker : MonoBehaviour
{
private enum State { Main, Settings };
[SerializeReference] private State state;
public void InvokeMenu(MenuInvoker currState)
{
switch (currState.state)
{
case State.Main:
Debug.Log("Main");
break;
case State.Settings:
Debug.Log("Settings");
break;
default:
Debug.Log("Default Menu");
break;
}
}
}

Create EventSystem from script

I'm writing a Unity editor script and need to make sure that an (UI) Event System exists so I want to create one if it's not already there. But the EventSystem class and StandaloneInputModule class can nowhere be found when trying to import it to a script. What's the matter with this? I can't find any other info on this matter either.
Yes, you can create an EventSystem from the script. As any other component, create a GameObject and add the desired component to it.
using UnityEngine;
using UnityEngine.EventSystems;
public class CreateEventSystem : MonoBehaviour
{
void Start()
{
if (FindObjectOfType<EventSystem>() == null)
{
var eventSystem = new GameObject("EventSystem", typeof(EventSystem), typeof(StandaloneInputModule));
}
}
}
When you add an UI item, the EventSystem object is automatically added. Just drag it into your Project to make it a prefab so you can use it to be instantiated just like any game object.
public GameObject eventPrefab;
void Start(){
if(GameObject.Find("EventSystem") == null){
Instantiate(eventPrefab);
}
}

Get EditText data on swipe to next Fragment

I have three fragments in a view pager:
A -> B -> C
I would like to get the strings of my two edittexts in Fragment A on swipe to Fragment B to show them in Fragment B. The edittext data may be changed up until the swipe.
Someone has suggested listening for typing and sending data after each one, but the callbacks I know for that change state EVERY key click (which can be expensive). How do I this without using buttons, since their right next to each other, for a more delightful experience?
You can check the data of the EditText on swipe ; if it's not null, then you can send it to any other fragment using Bundle since you are dealing with fragments
With help from #I. Leonard I found a solution here.
It was deprecated so I used the newer version. I put the below code in my fragment class because I needed access to the data without complicating things. It works like a charm!
On the page listener callback, I suggest, calling an interface for inter-fragment communication to do your actions on your home activity or to call the appropriate fragment that can do the work, from the activity.
// set content to next page on scroll start
vPager = (ViewPager) getActivity().findViewById(R.id.viewpager);
vPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
if (state == ViewPager.SCROLL_STATE_SETTLING) {
// ViewPager is slowing down to settle on a page
if (vPager.getCurrentItem() == 1) {
// The page to be settled on is the second (Preview) page
if (!areFieldsNull(boxOne.getText().toString(), boxTwo.getText().toString()))
// call interface method in view pager activity using interface reference
communicator.preview(boxOne.getText().toString(), boxTwo.getText().toString());
}
}
}
});

LibGDX - How to make a touchable image?

so I'm developing a game for android in LibGDX and I've stumbled upon a problem: I have a scene with an image in it and I want to be able to click/touch the image and make stuff happen after doing so.
I've been trying to google a solution for the past day but I keep on missing something vital. Here's my code:
public class ScreenSplash implements Screen {
private Texture textureGlobe = new Texture(Gdx.files.internal("graphics/splash.png"));
private Image imageGlobe = new Image((new TextureRegion(textureGlobe)));
public ScreenSplash() {
imageGlobe.addListener(new InputListener() {
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
Gdx.app.log(Game.LOG, "image clicked");
return true;
}
});
stageGame.addActor(imageGlobe);
}
...
}
I've also heard that I'm supposed to put this somewhere:
Gdx.input.setInputProcessor(inputProcessor);
But I don't really know what to do with it.
Your Stage is your InputProcessor so do something like Gdx.input.setInputProcessor(stageGame);. The Stage will route the events to the actors.
Ah, I've found out what the problem was.
I imported java.awt.event.InputEvent instead of com.badlogic.gdx.scenes.scene2d.InputEvent and the touchDown function wasn't properly overriden because of this.

ViewModels and IsolatedStorageSettings

Im working on a MVVM Windows phone app that displays weather info.
When the app loads up it opens MainPage.xaml. It makes a call the the service to get weather info and binds that data to the UI. Both Fahrenheit and Celcius info are returned but only one is displayed.
On the setting page, the user can select to view the temp in either Fahrenheit or Celcius.
The user can change this setting at any time and its stored in IsolatedStorageSettings.
The issue Im having is this:
when the user navigates to the Settings page and changes their preference for either Fahrenheit or Celcius, this change is not reflected on the main page.
This issue started me thinking about this in a broader context. I can see this being an issue in ANY MVVM app where the display depends on some setting in IsolatedStorage. Any time any setting in the IsoStore is updated, how does the ViewModels know this? When I navigate back in the NavigationStack from the settings page back to MainPage how can I force a rebind of the page?
The data in my model hasnt changed, only the data that I want to display has changed.
Am I missing something simple here?
Thanks in advance.
Alex
Probably you have code like this:
public double DisplayTemperature
{
get { return (IsCelsium) ? Celsium : Fahrenheit; }
}
And IsCelsium is:
public double IsCelsium
{
get { return (bool)settings["IsCelsium"]; }
set { settings["IsCelsium"] = value; }
}
So you need to add NotifyPropertyChanged event to notify UI to get new values from DisplayTemperature property:
public double IsCelsium
{
get { return (bool)settings["IsCelsium"]; }
set
{
settings["IsCelsium"] = value;
NotifyPropertyChanged("DisplayTemperature");
}
}
Take a look at Caliburn Micro. You could implement something similar or use CM itself. When using CM I don't even think about this stuff, CM makes it so simple.
When your ViewModel inherits from Screen there are life-cycle events that fire that you can override. For example, OnInitialize fires the very first time the ViewModel is Activated and OnActivate fires every time the VM is activated. There's also OnViewAttached and OnViewLoaded.
These methods are the perfect place to put logic to populate or re-populate data.
CM also has some special built in features for allowing one to easily tombstone a single property or an entire object graph into Iso or phone state.
ok, so Ive come up with a solution. Before I get to it, let me provide some background. The app that Im working on uses both MVVM Light and WP7Contrib. That being the case, I am using Funq for DI and the MVVMLight Toolkit. After I posted my initial question, I gave the question a bit more thought. I remembered a video that I watched a while back from MIX2011 called Deep Dive MVVM with Laurent Bugnion
http://channel9.msdn.com/Events/MIX/MIX11/OPN03
In it, he talks about just this problem (view models not living at the same time) on Windows Phone. The part in question starts around the 19 minute mark.
Anyway, after I remembered that and realized that the ViewModel locator is exposed in App.xaml, this became a trivial problem to solve. When the user changes the Fahrenheit/Celcius option on the setting page, I simply get a reference to the MainViewModel via the ViewModelLocator and reset the collection that is bound to the UI thus causing the bindings to update.
public bool AddOrUpdateValue(string Key, Object value)
{
bool valueChanged = false;
// If the key exists
if (settings.Contains(Key))
{
// If the value has changed
if (settings[Key] != value)
{
// Store the new value
settings[Key] = value;
valueChanged = true;
}
}
// Otherwise create the key.
else
{
settings.Add(Key, value);
valueChanged = true;
}
return valueChanged;
}
public bool ImperialSetting
{
get
{
return GetValueOrDefault<bool>(ImperialSettingKeyName, ImperialSettingDefault);
}
set
{
if (AddOrUpdateValue(ImperialSettingKeyName, value))
{
Save();
RaisePropertyChanged("ImperialSettingText");
var vml = new ViewModelLocator();
vml.MainViewModel.Cities = (App.Current as App).Cities;
}
}
}
It was a mistake on my part not to realize that I could get access to the viewModel via the ViewModelLocator. Hopefully this post saves someone else the time I burned on this issue.

Resources