Android: Changing Unity Scene from UI components outside the scene - android

I am trying to build an Android app that uses Unity for UI rendering where the user can perform some actions from outside the scene.
What this means is that say I have an activity where I have a unity scene as a subview. The rest of the screen is composed of native android views (buttons etc). I want to use these views to make changes to the unity scene such as to show a text field, add text, hide text, add text effects etc.
So far I have added the unity scene as a subview by following this answer and it works fine. I am new to Unity and I am not sure how I can manage and change the scene from views outside the scene. Is this even possible? I know if I add buttons to the scene itself when I create the scene in Unity then I can use those buttons to alter the scene.
But is this possible by UI components that are not a part of the scene? If yes how can I do this? I have tried to find info on this but couldn't find much. Thanks for reading.

Make communicator between Unity side and Android.
It's possible to do that technically, if you make following function in unity. I've just wrote here how unity and android communicate so
before use this code you need to see brief of integration between Unity and Android to use native plugin from Unity so see this link to do that.
https://docs.unity3d.com/Manual/PluginsForAndroid.html
After you understand that how to make plugin for android, then see codes. It will help you.
GameObject Name: LoadGameSceneObject, loadScene.cs
public class loadScene : MonoBehaviour
{
public static void LoadScene(string sceneName)
{
SceneManager.LoadScene(sceneName);
}
}
SceneLoadActivie.java
public static void SendMessageToUnity(String gameObjectName, String methodName, String message) throws Exception
{
Log.d("unity", gameObjectName + " " + methodName + " " + message);
final Class<?> player = Class.forName("com.unity3d.player.UnityPlayer");
player.getMethod("UnitySendMessage", String.class, String.class,
String.class).invoke(null, gameObjectName, methodName, message);
}
...
// call this function.
public void LoadScene()
{
SceneLoadActivie.SendMessageToUnity("LoadGameSceneObject", "LoadScene", "SomeScene");
}

Related

Choosing which Unity scene to play in Android Studio [duplicate]

I have integrated Unity in an Android activity (similar to this).
I now need to dynamically load a scene depending on user input.
I've tried replicating how Unity loads a scene, in the only way that I know an Android Activity is able to communicate with the UnityPlayer, but obviously doesn't work:
UnityPlayer.UnitySendMessage("Application", "LoadLevel", "9");
I know there are other ways of loading a scene in Unity, but I don't know how to call those from Android itself (also consider that UnitySendMessage only allows one parameter).
If you plan to load Unity activity from Android, you should create an empty scene. Call this this Main Menu, then make it the default scene that loads through the Build Settings. Make it index 0.
The goal of this empty scene is to load specific scene when script attached to it is called.
In this Main Menu scene, create a GameObject called SceneLoader then attach the script below to it:
public class SceneLoader : MonoBehaviour
{
public void loadScene(string sceneIndex)
{
UnityEngine.SceneManagement.SceneManager.LoadScene(Convert.ToInt16(sceneIndex));
}
}
You should also create a GameObject called SceneLoader in every other scene and attach the script above to all of them.
Now, load Unity Activity which automatically loads the default/empty scene. Since there is only one GameObject/SceneLoader in it, it will load very fast.
You can now load other scenes from Java with:
UnityPlayer.UnitySendMessage("SceneLoader", "loadScene", "9");

Get model object from ImageTarget Android

Currently, i'm trying to work with augment reality in android. For this task i'm using Unity + Vuforia.
So, i have made a scene, which is working, when i'm looking to specific object from my camera it shows me my model(basically 3d cat model with animation). I've done this according to tutorials like this:
text format tutorial and videos on youtube like this : video tutroial.
After this i've made android application, based on this scene, like this:
The result is Android project, which basically has one Activity and banch of assets and libs. The only connection with Unity that i see so far is UnityPlayer class, but it's just a ViewGroup, extended from FrameLayout
public class UnityPlayer extends FrameLayout implements com.unity3d.player.a.a
My goal: I need to overrideonClick on the view from Unity, which i've created(my 3d cat), something like when you click on cat on your phone, it will make some sound, and set some animation to it on after clicking. I have a model on the scene, just logically it has been converted to View class inside of Android, and i thought that it's just a child of UnityPlayer, but code like this :
mUnityPlayer.getChildAt(0).setOnClickListener
has no effect.
I want either have some object which will contain all the animations and other properties which model in unity has, or if it's impossible, learn how to set onClick listeners in Unity itself
I realize that this question might be unclear, and i would like to explain it in more details for those who would try to help.
If you need more info, just ask for it in comments. Thanks
Edit: As answer was suggesting, i could simply write a script for this, which i did, for using VirtualButton, it looks like this:
using UnityEngine;
using System.Collections.Generic;
using Vuforia;
public class VirtualButtonEventHandler : MonoBehaviour, IVirtualButtonEventHandler {
// Private fields to store the models
private GameObject kitten;
private GameObject btn;
/// Called when the scene is loaded
void Start() {
// Search for all Children from this ImageTarget with type VirtualButtonBehaviour
VirtualButtonBehaviour[] vbs = GetComponentsInChildren<VirtualButtonBehaviour>();
for (int i = 0; i < vbs.Length; ++i) {
// Register with the virtual buttons TrackableBehaviour
vbs[i].RegisterEventHandler(this);
}
// Find the models based on the names in the Hierarchy
kitten = transform.FindChild("kitten").gameObject;
btn = transform.FindChild("btn").gameObject;
kitten.SetActive(false);
btn.SetActive(true);
}
/// <summary>
/// Called when the virtual button has just been pressed:
/// </summary>
public void OnButtonPressed(VirtualButtonAbstractBehaviour vb) {
//Debug.Log(vb.VirtualButtonName);
//GUI.Label(new Rect(0, 0, 10, 5), "Hello World!");
}
/// Called when the virtual button has just been released:
public void OnButtonReleased(VirtualButtonAbstractBehaviour vb) {
}
}
As you can see, in Start() method i want to find and hide model, which called kitten, but it's not hiding
I've attached this script to virtual button object, i will provide a screen:
Edit: My mistake actually, for some reason, i had to attach VirtualButtonBehaviorHandler script to an ImageTarget, it's not that simple to understand for me, but i think i see some logic behind it right now.
But, for some unknow reason, if i'm adding this code:
public void OnButtonPressed(VirtualButtonAbstractBehaviour vb) {
//Debug.Log(vb.VirtualButtonName);
switch(vb.VirtualButtonName) {
case "btn":
kitten.setActive(true);
break;
}
}
It works instantly, even without touching on the button
Final edit: This was happenning, because i've add my button in database .xml, when i've removed button from it - everything worked, i'm marking the only one answer as correct, because it helped me
Brother Everything is possible if we do it. As per my understanding , what exactly you want to do is :
First : You need to clear some basic concept by reading blog & Tutorials:
As you mentioned object on which your white cyte :) cat render is "Marker"
In Unity Everything is gameobject you can write script to manipulate that gameobject (CAT) using script. which will be in either C#(Mono) or JavaScript for this work you can use Visual Studio or MonoDevelop by Unity
But before that please search for keywords on google
a) Touchevent, RayCastMenu Controle in unity: To handle Touch
b) MonoBehaviour class, Start() , Update(), OnGUI() method in Unity
You can identify any gameObject by using its name or Tag which you can see or change in Inspector window
These are some basic things . Please follow vuforia developer portal to learn more:
https://developer.vuforia.com/library/
Now: Coming to your question:
According to me you wanna do some stuff on Click of your sweet cat .
Its simple, if simply you want to launch android activity on click of cat then there are 2 possible ways:
Create android project and import it in unity as Library project in Unity.
OR
create android activity from unity project with the help of C# script. Attach this script to any GameObject in scene.
Here I providing the example of second one : On click of Button It will launch Android Activity.
What you have to do is:
Replace Button GameObject By CAT GameObjectExport Project as Android and write activity with same name and package as mention in C# code to do whatever you want to
Here In my example I have explained:
How to popup GUI when Marker is detected using Unity+ Vuforia
How to launch android Activity from Unity Code on Specific event
How to handle Event in Unity
How to maintain GUI same with multiple Resolutions
Please Study code Carefully and read the comments also :)
using UnityEngine;
using System.Collections;
using Vuforia; //import Vuforia
using System;
public class ButtonPopup : MonoBehaviour, ITrackableEventHandler
{
float native_width= 1920f;// Native Resolution to maintain resolution on different screen size
float native_height= 1080f;
public Texture btntexture;// drag and drop any texture in inspector window
private TrackableBehaviour mTrackableBehaviour;
private bool mShowGUIButton = false;
void Start () {
mTrackableBehaviour = GetComponent<TrackableBehaviour>();
if (mTrackableBehaviour) {
mTrackableBehaviour.RegisterTrackableEventHandler(this);
}
}
public void OnTrackableStateChanged(
TrackableBehaviour.Status previousStatus,
TrackableBehaviour.Status newStatus)
{
if (newStatus == TrackableBehaviour.Status.DETECTED ||
newStatus == TrackableBehaviour.Status.TRACKED ||
newStatus == TrackableBehaviour.Status.EXTENDED_TRACKED)
{
mShowGUIButton = true;// Button Shown only when marker detected same as your cat
}
else
{
mShowGUIButton = false;
}
}
void OnGUI() {
//set up scaling
float rx = Screen.width / native_width;
float ry = Screen.height / native_height;
GUI.matrix = Matrix4x4.TRS (new Vector3(0, 0, 0), Quaternion.identity, new Vector3 (rx, ry, 1));
Rect mButtonRect = new Rect(1920-215,5,210,110);
if (!btntexture) // This is the button that triggers AR and UI camera On/Off
{
Debug.LogError("Please assign a texture on the inspector");
return;
}
if (mShowGUIButton) {
// different screen position for your reference
//GUI.Box (new Rect (0,0,100,50), "Top-left");
//GUI.Box (new Rect (1920 - 100,0,100,50), "Top-right");
//GUI.Box (new Rect (0,1080- 50,100,50), "Bottom-left");
//GUI.Box (new Rect (Screen.width - 100,Screen.height - 50,100,50), "Bottom right");
// draw the GUI button
if (GUI.Button(mButtonRect, btntexture)) {
// do something on button click
OpenVideoActivity();
}
}
}
public void OpenVideoActivity()
{
var androidJC = new AndroidJavaClass("com.unity3d.player.UnityPlayer”);// any package name maintain same in android studio
var jo = androidJC.GetStatic<AndroidJavaObject>("currentActivity");
// Accessing the class to call a static method on it
var jc = new AndroidJavaClass("com.mobiliya.gepoc.StartVideoActivity”);//Name of android activity
// Calling a Call method to which the current activity is passed
jc.CallStatic("Call", jo);
}
}
Remember : In Unity everything is GameObject and you can write script to manipulate any GameObject
Edit: Info for Virtual Button
Virtual Buttons detect when underlying features of the target image are obscured from the camera view. You will need to place your button over an area of the image that is rich in features in order for it to reliably fire its OnButtonPressed event. To determine where these features are in your image, use the Show Features link for your image in the Target Manager.
Choose areas in the images that have dimensions of approximately 10% of the image target’s size.
Here is example in image i have simplify for you:
Register the Virtual Button:
To add a virtual button to an image target, add the VirtualButton element and its attributes to the ImageTarget element in the .xml file.
XML Attributes:
Name - a unique name for the button
Rectangle - defined by the four corners of the rectangle in the
target's coordinate space
Enabled - a boolean indicating whether the button should be enabled
by default
Sensitivity - HIGH, MEDIUM, LOW sensitivity to occlusion
You can get .Xml file in streamingAsset folder in unity project .
<ImageTarget size="247 173" name="wood">
<VirtualButton name="red" sensitivity="HIGH" rectangle="-108.68 -53.52 -75.75 -65.87"
enabled="true" />
<VirtualButton name="blue" sensitivity="LOW" rectangle="-45.28 -53.52 -12.35 -65.87"
enabled="true" />
<VirtualButton name="yellow" sensitivity="MEDIUM" rectangle="14.82 -53.52 47.75 -65.87"
enabled="true" />
<VirtualButton name="green" rectangle="76.57 -53.52 109.50 -65.87"
enabled="true" />
</ImageTarget>
After Registering Virtual Button Code is simple then:
public class Custom_VirtualButton : MonoBehaviour, IVirtualButtonEventHandler
{
// Use this for initialization
void Start () {
// here it finds any VirtualButton Attached to the ImageTarget and register it's event handler and in the
//OnButtonPressed and OnButtonReleased methods you can handle different buttons Click state
//via "vb.VirtualButtonName" variable and do some really awesome stuff with it.
VirtualButtonBehaviour[] vbs = GetComponentsInChildren<VirtualButtonBehaviour>();
foreach (VirtualButtonBehaviour item in vbs)
{
item.RegisterEventHandler(this);
}
}
// Update is called once per frame
void Update () {
}
#region VirtualButton
public void OnButtonPressed(VirtualButtonAbstractBehaviour vb)
{
Debug.Log("Helllllloooooooooo");
}
public void OnButtonReleased(VirtualButtonAbstractBehaviour vb)
{
Debug.Log("Goooooodbyeeee");
}
#endregion //VirtualButton
}
and after writing this code you have to go to StreamingAsset/QCAR and find your ImageTarget XML Association & do something like this:
<?xml version="1.0" encoding="UTF-8"?>
<QCARConfig xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="qcar_config.xsd">
<Tracking>
<ImageTarget name="marker01" size="100.000000 100.000000">
<VirtualButton name="red" rectangle="-49.00 -9.80 -18.82 -40.07" enabled="true" />
</ImageTarget>
</Tracking>
</QCARConfig>
Best of Luck :) Bdw CAT is so cute:)

Create and change to new view with React Native

We're currently working on an app for one of our customers, and we've decided to use React Native as the technology to use for creating the app.
I'm pretty new to this technology, and I'm used to developing apps with either C# or Java, where I have full-fledged IDEs that provide all the functionality I need.
I'm currently creating a login screen, and would like to change to different views, depending on the type of login (e.g.: Facebook, Google, Twitter, Email, etc.).
How do I go about doing this. As I mention, with an IDE, it'd be a shortcut like SHIFT+ALT+A or something to create a new item, select type, name it and the IDE does the rest.
Do I have to create a new xx.android/ios.js file, and somehow call that, or do I need to go in to the native backend of the different projects?
What I tried was something along the lines of:
class Class extends Component {
render() {
<UI code here>
<Button onPress={this.eventHandler}
}
eventHandler(event) {
var xxLogin = new xxLogin();
xxLogin.render();
}
}
class xxLogin extends Component {
render() {
<UI code here>
}
}
But that failed, which I expected.
Thanks in advance for any help!
P.S.: I'm using Mac OS X El Capitan, if that helps.

Xamarin Forms Custom Renderer for Android not displaying

I am trying to render a checkbox in a Xamarin Forms app. There is nothing rendered at runtime, as far as I can tell the renderer is not even getting called.
Does anyone understand what I am missing or doing incorrectly?
Here is my class in Forms:
public class LegalCheckbox : View
{
public LegalCheckbox ()
{
}
}
And my custom renderer class in Droid:
public class CheckBoxRenderer : ViewRenderer<LegalCheckbox, CheckBox>
{
protected override void OnElementChanged (ElementChangedEventArgs<LegalCheckbox> e)
{
base.OnElementChanged (e);
CheckBox control = new Android.Widget.CheckBox(this.Context);
control.Checked = false;
control.Text = "I agree to terms";
control.SetTextColor (Android.Graphics.Color.Rgb (60, 60, 60));
this.SetNativeControl(control);
}
}
Along with the Assembly Directive:
[assembly: ExportRenderer(typeof(demo.LegalCheckbox), typeof(demo.Droid.CheckBoxRenderer))]
Took your code and fired up a new project with it. The code appears to function fine.
Only thin I can think that might be causing you an issue is the location of you assembly attribute. I typically place them just above the namespace declaration in the same file as my renderer.
I threw what I created up on my github maybe you can spot the difference.
https://github.com/DavidStrickland0/Xamarin-Forms-Samples/tree/master/RendererDemo
#Thibault D.
Xlabs isn't a bad project but its basically just all the code the opensource community came up with during the first year or so of Xamarin.Forms life. Its not really "Their Labs projects" and considering how much of it is marked up with Alpha Beta and the number of bugs in their issues page it's probably best not to imply that the Xamarin company has anything to do with it.
I am not sure if that is the issue but it would make more sense to me if your LegalCheckbox would inherit from a InputView rather than View.
Also, even if Xamarin.Forms does not have a Checkbox control you can still have a look at their "Labs" project here:
https://github.com/XLabs/Xamarin-Forms-Labs/wiki/Checkbox-Control
(And I can actually see that they inherit from View...)

Call a touch function using NGUI/Unity3D?

I have a game that is using GUITextures for buttons but it isn't working on different resoltutions. So I was told NGUI would do it very easily. But I already have the code written for the GUITexture buttons.
How do I do it for NGUI buttons using the same textures? I've searched everywhere and can not find any answers....the NGUI forums are not much help.
Your Gameobject should have any type of collider component then in script do the following:
//Use UIEventListener to bind your gameobject with your desired method
public GameObject YOUR_BUTTON_GAMEOBJECT;
UIEventListener.Get(YOUR_BUTTON_GAMEOBJECT).onClick += YOUR_METHOD_NAME;
//METHOD SIGNATURES
void YOUR_METHOD_NAME(GameObject gameObject){
//On Click Stuff
}
Hope this helps

Categories

Resources