How to fade between two 360 video background skyboxes in Unity - c#

I want to be able to switch between two Panoramic skyboxes with 360 video on them with an effect where one video fades into the other on command. How would I accomplish this?
I currently have my scene switching skyboxes with no fade in between. I dont know if I will be able to achieve the effect I am looking for without changing the current solution
public class VideoChange : MonoBehaviour
{
public int vidindex;
public Material[] skyboxes;
public GameObject menu;
public TextMeshPro debugText;
void Start()
{
RenderSettings.skybox = skyboxes[vidindex];
DynamicGI.UpdateEnvironment();
}
void Update()
{
if (OVRInput.GetDown(OVRInput.Button.One))
{
if(vidindex != skyboxes.Length -1)
{
vidindex++;
}
else
{
vidindex = 0;
}
RenderSettings.skybox = skyboxes[vidindex];
DynamicGI.UpdateEnvironment();
Debug.Log("h3er");
}
if (OVRInput.GetDown(OVRInput.Button.Two))
{
if (vidindex != 0)
{
vidindex--;
}
else
{
vidindex = skyboxes.Length - 1;
}
RenderSettings.skybox = skyboxes[vidindex];
DynamicGI.UpdateEnvironment();
Debug.Log("h3er");
}
}

Related

How to scale only one game object in the AR scene in Unity?

so I have like 5 game object in my scene but I only scale each of them separately. However when I try to do that all of them start scaling simultaneously. Also, I have a placement indicator that would be used to instantiate the object on the plane. It seems that instead of the object itself, the placement indicator is the one that gets scaled. How should I fix that?
I have tried deactivating the placement indicator but did not work.
Here is the code for instantiating objects:
I limited the obj number to 5.
I use this script instead of the usual "PlaceonPlane" script.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR.ARFoundation;
using UnityEngine.Experimental.XR;
using UnityEngine.UI;
using UnityEngine.XR.ARSubsystems;
public class ARTaptoPlaceObject : MonoBehaviour
{
private ARSessionOrigin arOrigin;
GameObject spawnedobj;
public GameObject placementIndicator;
private ARRaycastManager arRaycast;
public Pose placementPose;
public UIContoller sc;
public bool placementPoseIsValid = false;
private int count;
private string valu;
string prefabs;
void Start()
{
arOrigin = FindObjectOfType<ARSessionOrigin>();
arRaycast = FindObjectOfType<ARRaycastManager>();
count = 0;
}
// Update is called once per frame
void Update()
{
UpdatePlacementPose();
UpdatePlacementIndicator();
for (var i = 0; i < Input.touchCount; ++i)
{
if (Input.GetTouch(i).phase == TouchPhase.Began)
{
if (placementPoseIsValid && Input.GetTouch(i).tapCount == 2)
{
PlaceObject();
}
}
}
}
public void PlaceObject()
{
if (count <= 4)
{
if (sc.objectToPlace != null)
{
spawnedobj = Instantiate(sc.objectToPlace, placementPose.position, placementPose.rotation);
arOrigin.MakeContentAppearAt(spawnedobj.transform, spawnedobj.transform.position, spawnedobj.transform.rotation);
count++;
}
}
else
{
placementIndicator.SetActive(false);
}
}
private void UpdatePlacementIndicator()
{
if (placementPoseIsValid && count <= 4 && sc.active == false)
{
placementIndicator.SetActive(true);
placementIndicator.transform.SetPositionAndRotation(placementPose.position, placementPose.rotation);
}
else
{
placementIndicator.SetActive(false);
}
}
private void UpdatePlacementPose()
{
var screenCenter = Camera.current.ViewportToScreenPoint(new Vector3(0.5f, 0.5f));
var hits = new List<ARRaycastHit>();
arRaycast.Raycast(screenCenter, hits, UnityEngine.XR.ARSubsystems.TrackableType.Planes);
placementPoseIsValid = hits.Count > 0;
if (placementPoseIsValid)
{
placementPose = hits[0].pose;
var cameraForward = Camera.current.transform.forward;
var cameraBearing = new Vector3(cameraForward.x, 0, cameraForward.z).normalized;
placementPose.rotation = Quaternion.LookRotation(cameraBearing);
}
}
}
and here is the Scaler script that's attached to the button that would scale the object.
public class Scaler : MonoBehaviour
{
public UIContoller uc;
public ARTaptoPlaceObject ap;
private GameObject ReferenceToScale;
public void OnValueChange()
{
ReferenceToScale = (UnityEngine.GameObject)Resources.Load(uc.s_count, typeof(GameObject));
Vector3 t = ReferenceToScale.transform.localScale;
Vector3 scaleValue = t * 1.1f;
ReferenceToScale.transform.localScale = scaleValue;
}
Also the "objectToPlace" itself is in the "UI.Controller" script as I could not view it in the scene when it was in the "ARTaptoPlace" script

How to make an object slide left and right automaticly in Unity 5.6? [duplicate]

This question already has an answer here:
Move GameObject back and forth
(1 answer)
Closed 5 years ago.
I'm currently developing a game in Unity 3D with c#. I developed some levels, and now I want to make some levels with auto moving cubes(the thematic of the game is cubes). I searched a lot on the internet but I don't find nothing wich satisfy me. Can someone help me? I really need help. Sorry if there are some grammare errors.
Create a new Script an name it SimpleTranslator.cs then copy and paste the below code.
using UnityEngine;
namespace TransformUtility
{
public class SimpleTranslator : MonoBehaviour
{
[Tooltip("The local target position towards we translate this gameObject. A red line is drawn.")]
public Vector3 m_localTargetPosition = new Vector3(0, 0, 5);
public float speed = 1;
public bool pingPong;
public bool translateOnAwake = true;
public new AudioSource audio;
Vector3 m_initialPosition, m_targetPosition;
Transform m_transform;
void Awake()
{
m_transform = transform;
m_initialPosition = m_transform.position;
SetTargetPosition(m_localTargetPosition);
enabled = translateOnAwake;
}
void FixedUpdate()
{
if (audio && !audio.isPlaying)
audio.Play();
m_transform.position = Vector3.MoveTowards(m_transform.position, m_targetPosition, speed * Time.deltaTime);
if (m_transform.position == m_targetPosition)
{
if (pingPong)
{
SwitchDirection();
}
else
{
enabled = false;
if (audio)
audio.Stop();
}
}
}
public bool isTranslating
{
get
{
return enabled;
}
}
public void SwitchDirection()
{
enabled = true;
if (m_transform.position == m_initialPosition)
{
SetTargetPosition(m_localTargetPosition);
}
else
{
m_targetPosition = m_initialPosition;
}
}
public void MoveToTargetPosition()
{
enabled = true;
SetTargetPosition(m_localTargetPosition);
}
public void MoveToInitialPosition()
{
m_targetPosition = m_initialPosition;
enabled = true;
}
public bool isInInitialPosition
{
get
{
return m_transform.position == m_initialPosition;
}
}
public bool isInTargetPosition
{
get
{
return m_transform.position == m_initialPosition + m_transform.TransformDirection(m_localTargetPosition);
}
}
private void SetTargetPosition(Vector3 localPosition)
{
m_targetPosition = m_initialPosition + transform.TransformDirection(localPosition);
#if UNITY_EDITOR
m_endPositionDebug = m_targetPosition;
#endif
}
#if UNITY_EDITOR
Vector3 m_endPositionDebug;
void OnDrawGizmos()
{
if (!Application.isPlaying)
{
Debug.DrawRay(transform.position, transform.TransformDirection(m_localTargetPosition), Color.red);
}
else
{
Debug.DrawLine(m_initialPosition, m_endPositionDebug, Color.red);
}
}
#endif
}
}

How can I mouse camera view by mouse for fps in unity 5

I am just looking into Unity5 since it is my school project. They told me to make a fps game and I try to make a fps that will make the camera rotate by Q and E but I cannot move the camera by mouse. And when I want to input mouse , I can not move my fps character at all. Here my code:
using UnityEngine;
public class Player : MonoBehaviour {
private MazeCell currentCell;
private MazeDirection currentDirection;
public void SetLocation (MazeCell cell) {
if (currentCell != null) {
currentCell.OnPlayerExited();
}
currentCell = cell;
transform.localPosition = cell.transform.localPosition;
currentCell.OnPlayerEntered();
}
private void Move (MazeDirection direction) {
MazeCellEdge edge = currentCell.GetEdge(direction);
if (edge is MazePassage) {
SetLocation(edge.otherCell);
}
}
private void Look (MazeDirection direction) {
transform.localRotation = direction.ToRotation();
currentDirection = direction;
}
private void Update () {
if (Input.GetKeyDown(KeyCode.W) || Input.GetKeyDown(KeyCode.UpArrow)) {
Move(currentDirection);
}
if (Input.GetKeyDown(KeyCode.D) || Input.GetKeyDown(KeyCode.RightArrow)) {
Move(currentDirection.GetNextClockwise());
}
if (Input.GetKeyDown(KeyCode.S) || Input.GetKeyDown(KeyCode.DownArrow)) {
Move(currentDirection.GetOpposite());
}
if (Input.GetKeyDown(KeyCode.A) || Input.GetKeyDown(KeyCode.LeftArrow)) {
Move(currentDirection.GetNextCounterclockwise());
}
if (Input.GetKeyDown(KeyCode.Q)) {
Look(currentDirection.GetNextCounterclockwise());
}
if (Input.GetKeyDown(KeyCode.E)) {
Look(currentDirection.GetNextClockwise());
}
}
}
first of all you should remoove the "else if"s in your update function and replace them with a simple "if".
because what happens is that the following functions are skipped as soon as one of your if statements is true.
that should fix it.
try this:
public class Player : MonoBehaviour {
//Position of mouse since last change in viewdirection
private float mousePosLast;
//Tollerance of mouse input
//this is optional but makes the the input not that sensitive
public float mouseTollerance;
//sets the correct position of mouse on start
public void Start () {
mousePosLast = Input.mousePosition.x;
}
public void Update () {
/*
...other update code...
*/
if (Input.GetKeyDown(KeyCode.Q)) {
Look(currentDirection.GetNextCounterclockwise());
}
if (Input.GetKeyDown(KeyCode.E)) {
Look(currentDirection.GetNextClockwise());
}
//check if change in mouse position is big enougth to trigger camera rotation
if(Mathf.Abs(Input.mousePosition.x - mousePosLast) > mouseTollerance){
//check whether to turn right or left
if(Input.mousePosition.x - mousePosLast > 0){
Look(currentDirection.GetNextCounterclockwise());
}else{
Look(currentDirection.GetNextClockwise());
}
}
}
private void Look (MazeDirection direction) {
transform.localRotation = direction.ToRotation();
currentDirection = direction;
//set mousePosLast to current mouseposition on every change -> avoids strange effects
mousePosLast = Input.mousePosition.x;
}
}

Unity3d Interactive pause menu that has uses Input.GetAxis to Navigate the new UI

Okay So I'm trying to create an interactive pause menu that has access to Input.GetAxis using Unity 4.6's new UI.
As long as the Navigation relationships are set up for the selectable elements (In my case a series of buttons) and Interactable is set to true then the UI works just fine but, when I set the Time.timeScale = 0.0f; then keyboard input navigation no longer works. However the mouse input clicks and animation still work as intended.
I've tried several different ways to get around the time scale problem and the best I've got so far is checking the value returned from Input.GetAxis() while in the body of the Update message of the MonoBehavor base object. This somewhat works but my results are either the very top or very bottom of the Button selected collection. I'm thinking this is because update gets called a great deal more than FixedUpdate and would make sense if my console printed out more call to the method that moves up and down the selection. So with that I'm thinking its one of those "office space" type errors, off by 1 decimal place or something silly but I just can't seem to see it. Otherwise I think my solution would be a fairly viable work around.
The following is an image of my Unity Setup with mentioned game objects in Unity 4.6 followed by my code.
public class PlayerInGameMenu : MonoBehaviour
{
public EventSystem eventSystem;
Selectable SelectedButton;
public Selectable Status;
public Selectable Settings;
public Selectable Save;
public Selectable Quit;
public bool Paused;
List<Selectable> buttons;
int selecteButtonIndex = 0;
public Canvas Menu;
void Start()
{
Menu.enabled = false;
buttons = new List<Selectable>();
buttons.Add(Status);
buttons.Add(Settings);
buttons.Add(Save);
buttons.Add(Quit);
SelectedButton = buttons[0];
}
void Update()
{
CheckInput();
if (Paused && !Menu.enabled)
{
ShowMenu();
}
else if (!Paused && Menu.enabled)
{
HideMenu();
}
}
void ShowMenu()
{
Paused = true;
Menu.enabled = true;
Time.timeScale = 0.0f;
}
void HideMenu()
{
if (Menu.enabled)
{
Paused = false;
Menu.enabled = false;
Time.timeScale = 1.0f;
}
}
void CheckInput()
{
if (cInput.GetKeyDown("Pause"))
{
Paused = !Paused;
SelectedButton = buttons[selecteButtonIndex];
eventSystem.SetSelectedGameObject(SelectedButton.gameObject, new BaseEventData(eventSystem));
}
if (Paused)
{
float v = cInput.GetAxis("Vertical");
//to attempt to cut down on the input sensitity I am checking 0.5 instead of just 0.0
if (v >= 0.5)
{
GoDown();
}
else if (v <= -0.5)
{
GoUp();
}
}
}
void GoDown()
{
//go to the last button available if we go past the index
if (selecteButtonIndex > buttons.Count - 1)
{
selecteButtonIndex = buttons.Count - 1;
}
else
{
selecteButtonIndex = selecteButtonIndex + 1;
}
}
//go to the first button available if we go past the index
void GoUp()
{
if (selecteButtonIndex < 0)
{
selecteButtonIndex = 0;
}
else
{
selecteButtonIndex = selecteButtonIndex - 1;
}
}
}
I know its in beta but I'm wondering if you are going to implement navigation why would you design it in such a way that Time.timeScale=0.0f; (the easy way to pause a game) does not work with the UI button navigation naturally. Problems for minds greater than I maybe? Or there is a simple way to do it and I just do not know what bit I need to flip.
I've also considered just freezing rigid bodies on pause but that seems like will require a huge time investment in my existing code base and will not be a universal solution across all game objects particularly colliders that do not rely on Rigid bodies and particle systems. I'm pretty open minded about solutions but it seems like there should be a really easy way to do this.
This worked like a charm:
var v = Input.GetAxisRaw("JoyY1"); // Or "Vertical"
if (Math.Abs(v) > ButtonThreashold)
{
var currentlySelected = EventSystem.currentSelectedGameObject
? EventSystem.currentSelectedGameObject.GetComponent<Selectable>()
: FindObjectOfType<Selectable>();
Selectable nextToSelect = null;
if (v > ButtonThreashold)
{
nextToSelect = currentlySelected.FindSelectableOnUp();
}
else if (v < -ButtonThreashold)
{
nextToSelect = currentlySelected.FindSelectableOnDown();
}
if (nextToSelect)
{
EventSystem.SetSelectedGameObject(nextToSelect.gameObject);
}
}
Okay so my solution to this problem was to utilize Time.realtimeSinceStartup to check for input on fixed intervals and develop an abstract class that inherits from MonoBehavior. What that looks like in code:
public abstract class RealtimeMonoBehavior:MonoBehaviour
{
public float updateInterval = 0.5F;
private double lastInterval;
void Start()
{
DefaultIntervalStart();
lastInterval = Time.realtimeSinceStartup;
RealtimeIntervalStart();
}
void Update()
{
DefaultIntervalUpdate();
float timeNow = Time.realtimeSinceStartup;
if (timeNow > lastInterval + updateInterval)
{
lastInterval = timeNow;
RealtimeIntervalUpdate();
}
}
public virtual void DefaultIntervalUpdate(){}
public virtual void DefaultIntervalStart(){}
public virtual void RealtimeIntervalStart(){}
public virtual void RealtimeIntervalUpdate(){}
}
And here is what my code looks like after implementing the change
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using Extensions;
using UnityEngine.EventSystems;
public class PlayerInGameMenu : RealtimeMonoBehavior
{
public EventSystem eventSystem;
Selectable SelectedButton;
public Selectable Status;
public Selectable Settings;
public Selectable Save;
public Selectable Quit;
public float ButtonThreashold;
public bool Paused;
List<Selectable> buttons;
int selectedButtonIndex;
public PlayerMovement PlayerMovement;
public Canvas Menu;
public override void RealtimeIntervalStart()
{
base.RealtimeIntervalStart();
Menu.enabled = false;
buttons = new List<Selectable>();
buttons.Add(Status);
buttons.Add(Settings);
buttons.Add(Save);
buttons.Add(Quit);
selectedButtonIndex = 0;
SelectedButton = buttons[selectedButtonIndex];
eventSystem.SetSelectedGameObject(SelectedButton.gameObject, new BaseEventData(eventSystem));
}
public override void DefaultIntervalUpdate()
{
base.DefaultIntervalUpdate();
if (cInput.GetKeyDown("Pause"))
{
Paused = !Paused;
}
}
public override void RealtimeIntervalUpdate()
{
base.RealtimeIntervalUpdate();
CheckInput();
if (Paused && !Menu.enabled)
{
ShowMenu();
}
else if (!Paused && Menu.enabled)
{
HideMenu();
}
}
void ShowMenu()
{
Paused = true;
Menu.enabled = true;
Time.timeScale = 0.0f;
}
void HideMenu()
{
if (Menu.enabled)
{
Paused = false;
Menu.enabled = false;
Time.timeScale = 1.0f;
}
}
void CheckInput()
{
if (Paused)
{
float v = Input.GetAxisRaw("Vertical");
if (v > ButtonThreashold)
{
GoUp();
}
else if (v < -ButtonThreashold)
{
GoDown();
}
SelectedButton = buttons[selectedButtonIndex];
eventSystem.SetSelectedGameObject(SelectedButton.gameObject, new BaseEventData(eventSystem));
}
}
void GoDown()
{
if (selectedButtonIndex < buttons.Count - 1)
{
selectedButtonIndex = selectedButtonIndex + 1;
}
}
void GoUp()
{
if (selectedButtonIndex > 0)
{
selectedButtonIndex = selectedButtonIndex - 1;
}
}
}
Nod to imapler, Input.GetAxisRaw feels better for checking the input.

C# GUI Texture Button Script

I've finally found a script that can be used with a GUI Button in an IOS project. I am using Unity3d game engine. I'm a little familiar with JavaScript buttons and animation but am not familiar at all with C#. My problem is not knowing were to write the function that will play a queued animation in the C# button script when the button is touched. Below is copy of the IOS Button Script and then the code I have to play the queued animation.
using UnityEngine;
using System.Collections;
public enum Btn
{
normal,
hover,
armed
}
[System.Serializable] // Required so it shows up in the inspector
public class ButtonTextures
{
public Texture normal=null;
public Texture hover=null;
public Texture armed=null;
public ButtonTextures() {}
public Texture this [ButtonState state]
{
get
{
switch(state)
{
case ButtonState.normal:
return normal;
case ButtonState.hover:
return hover;
case ButtonState.armed:
return armed;
default:
return null;
}
}
}
}
[RequireComponent(typeof(GUITexture))]
[AddComponentMenu ("GUI/Button")]
public class GuiButton : MonoBehaviour
{
public GameObject messagee;
public string message = "";
public string messageDoubleClick = "";
public ButtonTextures textures;
protected int state = 0;
protected GUITexture myGUITexture;
private int clickCount = 1;
private float lastClickTime = 0.0f;
static private float doubleClickSensitivity = 0.5f;
protected virtual void SetButtonTexture(ButtonState state)
{
if (textures[state] != null)
{
myGUITexture.texture = textures[state];
}
}
public virtual void Reset()
{
messagee = gameObject;
message = "";
messageDoubleClick = "";
}
public bool HitTest(Vector2 pos)
{
return myGUITexture.HitTest(new Vector3(pos.x, pos.y, 0));
}
public virtual void Start()
{
myGUITexture = GetComponent(typeof(GUITexture)) as GUITexture;
SetButtonTexture(ButtonState.normal);
}
public virtual void OnMouseEnter()
{
state++;
if (state == 1)
SetButtonTexture(ButtonState.hover);
}
public virtual void OnMouseDown()
{
state++;
if (state == 2)
SetButtonTexture(ButtonState.armed);
}
public virtual void OnMouseUp()
{
if (Time.time - lastClickTime <= doubleClickSensitivity)
{
++clickCount;
}
else
{
clickCount = 1;
}
if (state == 2)
{
state--;
if (clickCount == 1)
{
if (messagee != null && message != "")
{
messagee.SendMessage(message, this);
}
}
else
{
if (messagee != null && messageDoubleClick != "")
{
messagee.SendMessage(messageDoubleClick, this);
}
}
}
else
{
state --;
if (state < 0)
state = 0;
}
SetButtonTexture(ButtonState.normal);
lastClickTime = Time.time;
}
public virtual void OnMouseExit()
{
if (state > 0)
state--;
if (state == 0)
SetButtonTexture(ButtonState.normal);
}
#if (UNITY_IPHONE || UNITY_ANDROID)
void Update()
{
int count = Input.touchCount;
for (int i = 0; i < count; i++)
{
Touch touch = Input.GetTouch(i);
if (HitTest(touch.position))
{
if (touch.phase == TouchPhase.Ended || touch.phase == TouchPhase.Canceled)
{
SetButtonTexture(ButtonState.normal);
}
else
{
SetButtonTexture(ButtonState.armed);
}
if (touch.phase == TouchPhase.Began)
{
if (touch.tapCount == 1)
{
if (messagee != null && message != "")
{
messagee.SendMessage(message, this);
}
}
else if (touch.tapCount == 2)
{
if (messagee != null && messageDoubleClick != "")
{
messagee.SendMessage(messageDoubleClick, this);
}
}
}
break;
}
}
}
#endif
}
Most of this seems to deal with button states, where my touch button only has one state, which is 'normal'. Should references to 'hover' and armed just be deleted? I also get an error in the console saying; "the type or namespace "Button State" could not be found. Are you missing a using directive or an assembly reference?"
The code for C# GUI Button play queued animation I want to insert reads like this:
using UnityEngine;
using System.Collections;
public class example : MonoBehaviour {
void Update() {
if (Input.GetButtonDown("Btn"))
animation.PlayQueued("shoot", QueueMode.PlayNow);
}
}
I suppose of queued animation script snippet; Input.GetButtondown....would change to
void Update() {
if(Input.GetTouch("Btn"))
animation.PlayQueued("shoot", QueueMode.PlayNow);
}
and be inserted at about line 148 of the GUI Button script. Please help me if you can, I'm
feeling down. Seriously! Any help in reformatting this script would be greatly appreciated
and used as a template as I have two other GUI buttons to setup. It maybe asking a lot or what's a heaven for?
Respectfully,
Digital D
an analog man,
in a digital world
Okay, there's a lot going on in the script, but it appears to be designed so you don't have to modify it.
What you need to do is go to the object that will be playing the animation, and create a function on it that you wish to be called when the button is clicked.
So something like (you can do this in JS if you like):
public class ShootyMan : MonoBehaviour {
public void Shoot() {
animation.PlayQueued("shoot", QueueMode.PlayNow);
}
}
Now, look at the button in the inspector. I'm not sure if you're familiar with how messaging works in Unity, but basically the button will send a "message" to a "messagee". (ie. it will call a function of name message on any script attached to the messagee).
Set the "messagee" to the GameObject with the "Shoot" function. And set the message to the string "Shoot".

Categories