Create EventSystem from script - events

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);
}
}

Related

item dropping system - how can i use a prefab correctly here?

my code is pretty simple, but im quite new to unity... im trying to make it so i can drop my items on the ground when i drag the out of my inventory, but cant quite manage to do so, with a few consistent errors. I have a prefab (just learned of those today), which im trying to change its sprite renderer and spawn it. Heres my code:
public class ItemWorld : MonoBehaviour
{
private Transform prefab;
private Item item;
private SpriteRenderer spriteRenderer;
void Start()
{
prefab = Resources.Load("Prefabs/pfItemWorld") as GameObject;
//myPrefab = Resources.Load("Prefabs/pfItemWorld");
}
public static ItemWorld spawnItemWorld(Vector3 position, Item item)
{
Transform transform = Instantiate(prefab, position, Quaternion.identity);
ItemWorld itemWorld = transform.GetComponent<ItemWorld>();
itemWorld.SetItem(item);
return itemWorld;
}
private void Awake()
{
spriteRenderer = GetComponent<SpriteRenderer>();
}
public void SetItem(Item item)
{
this.item = item;
Rect spriteRect = new Rect(0, 0, item.itemIcon.width, item.itemIcon.height);
Sprite mySprite = Sprite.Create(item.itemIcon, spriteRect, new Vector2(0.5f, 0.5f));
spriteRenderer.sprite = mySprite;
}
}
My problem is i cant manage to load my prefab and use it in Instantiate without many errors...
What is wrong with my code?
Here are the errors:
(1) Assets\Scripts\ItemWorld.cs(12,18): error CS0029: Cannot implicitly convert type 'UnityEngine.GameObject' to 'UnityEngine.Transform' (yes, i know what this means, but how can i use a prefab without transform)
(2)Assets\Scripts\ItemWorld.cs(17,43): error CS0120: An object reference is required for the non-static field, method, or property 'ItemWorld.prefab'
I have tried to research but this is my last hope xd
Ill be happy for ANY help,
thanks ahead,
Gambizon
Prefabs are GameObjects and need to be instantiated and declared as such. private transform prefab should be private GameObject prefab.
After you've instantiated the object with
GameObject prefabObject = Instantiate(prefab, position, Quaternion.identity);
You can then use Transform transform = prefabObject.transform; to get the transform component of your newly instantiated prefab.
Also, if you make the prefab reference in the script public, and have this script attached to a GameObject, you can drag the prefab into the inspector so that you don't need Resources.Load("Prefabs/pfItemWorld") as GameObject, as the reference will already be there before run time.

How to create a never ending background service in Xamarin.Forms?

I am monitoring the user's location every 15 minutes and I just want the application to continue sending the location even if the user closes the application in the taskbar.
I tried this sample but it's in Xamarin.Android https://learn.microsoft.com/en-us/xamarin/android/app-fundamentals/services/foreground-services i have to create a dependencyservice but i don't know how.
i have to create a dependencyservice but i don't know how.
First, create an Interface in the Xamarin.forms project:
public interface IStartService
{
void StartForegroundServiceCompat();
}
And then create a new file let's call it itstartServiceAndroid in xxx.Android project to implement the service you want:
[assembly: Dependency(typeof(startServiceAndroid))]
namespace DependencyServiceDemos.Droid
{
public class startServiceAndroid : IStartService
{
public void StartForegroundServiceCompat()
{
var intent = new Intent(MainActivity.Instance, typeof(myLocationService));
if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
{
MainActivity.Instance.StartForegroundService(intent);
}
else
{
MainActivity.Instance.StartService(intent);
}
}
}
[Service]
public class myLocationService : Service
{
public override IBinder OnBind(Intent intent)
{
}
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
// Code not directly related to publishing the notification has been omitted for clarity.
// Normally, this method would hold the code to be run when the service is started.
//Write want you want to do here
}
}
}
Once you want to call the StartForegroundServiceCompat method in Xamarin.forms project, you can use:
public MainPage()
{
InitializeComponent();
//call method to start service, you can put this line everywhere you want to get start
DependencyService.Get<IStartService>().StartForegroundServiceCompat();
}
Here is the document about dependency-service
For iOS, if the user closes the application in the taskbar, you will no longer be able to run any service. If the app is running, you can read this document about ios-backgrounding-walkthroughs/location-walkthrough
You might want to have a look at Shiny by Allan Ritchie. It's currently in beta but I would still suggest using it, as it will save you a lot of trouble writing this code yourself. Here's a blog post by Allan, explaining what you can do with Shiny in terms of background tasks - I think Scheduled Jobs are the thing you're looking for.

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;
}
}
}

Character Controller speed: running vs. walking

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.

How can I add a button to the stage in flex using only as3?

I am using the Flex SDK within visual studio and trying to dynamically add a button to the stage. Here is a quick example of what I am doing.
public class Test extends Sprite
{
public function Test()
{
init();
}
private function init():void
{
var btnBrowse:Button = new Button();
btnBrowse.label = "Browse";
btnBrowse.x = 0;
btnBrowse.y = 0;
btnBrowse.width=100;
btnBrowse.height=100;
addChild(btnBrowse);
}
}
Nothing seems to show up and the screen is still empty. I am importing mx.controls.* for the button. Could that create an issue since I am not using mxml only as3?
You can't use Flex framework controls in an AS3 Only project. If you are trying to avoid MXML then just create a new Flex Project where the root tag is like:
<FooApplication xmlns="*"/>
And create a new AS3 Class like:
package {
import mx.core.Application;
public class FooApplication extends Application {
// now override something like createChildren to add a button.
}
}
Try changing the base class from Sprite to Canvas.

Resources