## OpenXR device not present in Start or Awake methods in Unity C# script

I’m developing a VR game using OpenXR in Unity (specifically developing on a Valve Index). When I try to access the input devices through the `InputDevices.GetDevices()` function, I get 0 devices back when I call this function from my script’s `Awake()` or `Start()` methods. But when I call the same function from my script’s `Update()` method, I see all the devices (e.g. head set, left controller, right controller).

Why can’t I see the devices in the `Awake()` or `Start()` methods?

## unity – How can a object be prevented from falling?

I tried to make projectile for a Spaceship for 3D game. But whenever I instanitate an projectile and make it move, ıt falls . I assume because of rigidbody but couldn’t find how to fix. I want projectile to move forward and not fall.

Those are components of projectile

Those are codes I used to keep projectile from falling.

``````void Update()
{
//transform.position += new Vector3(-1, 0, 0) * 0.1f;
//GetComponent<Rigidbody>().velocity = -transform.right * 100 * Time.deltaTime;
}
``````

## unity – Why when using editor script with handles with DrawSolidArc it’s not drawing any arc over the object?

This is the editor script is in the Assets/Editor

``````using UnityEngine;
using UnityEditor;

(CustomEditor(typeof(DrawSolidArc)))
public class DrawSolidArcEditor : Editor
{
public float arrowSize = 1;

void OnSceneGUI()
{
DrawSolidArc t = target as DrawSolidArc;

Handles.color = Color.blue;
Handles.Label(t.transform.position + Vector3.up * 2,
t.transform.position.ToString() + "nShieldArea: " +
t.shieldArea.ToString());

Handles.BeginGUI();
GUILayout.BeginArea(new Rect(Screen.width - 100, Screen.height - 80, 90, 50));

if (GUILayout.Button("Reset Area"))
t.shieldArea = 5;

GUILayout.EndArea();
Handles.EndGUI();

Handles.color = new Color(1, 1, 1, 0.2f);
Handles.DrawSolidArc(t.transform.position, t.transform.up, -t.transform.right,
180, t.shieldArea);

Handles.color = Color.white;
t.shieldArea = Handles.ScaleValueHandle(t.shieldArea,
t.transform.position + t.transform.forward * t.shieldArea,
t.transform.rotation, 1, Handles.ConeHandleCap, 1);
}
}
``````

And the mono script for example this script is attached to a simple 3d cube :

``````using UnityEngine;

(ExecuteInEditMode)
public class DrawSolidArc : MonoBehaviour
{
public float shieldArea = 5;
}
``````

but there is nothing around the cube. not also near it nothing.
it should draw arch in the editor.

Later I want to be able to use the mouse with a click down and drag to be able to change the arc size but for not it’s not drawing any arc.

I took the example from the unity official docs :

https://docs.unity3d.com/540/Documentation/ScriptReference/Handles.DrawSolidArc.html

I noticed now also for example that I don’t see the gui button in the inspector of the object that the mono script is attached to :

``````if (GUILayout.Button("Reset Area"))
``````

not sure what’s wrong with the editor script.

This is working. I still wonder why the unity docs example didn’t work but this is working and I don’t need the editor script. The problem with this script is that I must to turn on the Gizmos in the editor and I don’t want to make it turned on all the time. So it’s working but not as I wanted.

I want to draw the arc without the gizmos.

``````using UnityEngine;

(ExecuteInEditMode)
public class DrawSolidArc : MonoBehaviour
{
public Vector3 offset = Vector3.one;
public float fieldOfViewAngle = 20;
public float viewDistance = 4;
public bool usePhysics2D = false;

public void OnDrawGizmos()
{
DrawLineOfSight(this.transform, offset, fieldOfViewAngle, viewDistance, usePhysics2D);
}
public static void DrawLineOfSight(Transform transform, Vector3 positionOffset, float fieldOfViewAngle, float viewDistance, bool usePhysics2D)
{
#if UNITY_EDITOR
var oldColor = UnityEditor.Handles.color;
var color = Color.yellow;
color.a = 0.1f;
UnityEditor.Handles.color = color;
var halfFOV = fieldOfViewAngle * 0.5f;
var beginDirection = Quaternion.AngleAxis(-halfFOV, (usePhysics2D ? Vector3.forward : Vector3.up)) * (usePhysics2D ? transform.up : transform.forward);
UnityEditor.Handles.DrawSolidArc(transform.TransformPoint(positionOffset), (usePhysics2D ? transform.forward : transform.up), beginDirection, fieldOfViewAngle, viewDistance);
UnityEditor.Handles.color = oldColor;
#endif
}
}
``````

## unity – How to access a property in an object’s method called by UnityEvent.Invoke()?

I have 3 objects in my Unity scene:

• `Planet`, with script `Planet`, property `actionableModel` and method `stopBuilding()`

``````public class Planet : MonoBehaviour
{
private GameObject _actionableModel;

// ...

public void stopBuilding()
{
// For debugging only
Planet planet = GameObject.Find("Planet").GetComponent<Planet>();
Debug.Log(planet.actionableModel);
Debug.Log(this.actionableModel);

}
}
``````
• `Actionable` with script `Actionable` which has `UnityEvent` property `onClick`, which calls `stopBuilding()` on a click event

``````public class Actionable : MonoBehaviour
{
public class OnClick : UnityEvent<GameObject> { }
public OnClick onClick = new OnClick();

// ...

void OnMouseDown()
{
onClick.Invoke(gameObject);
}
}
``````
• A Button, which calls `stopBuilding()` on click event.

When `stopBuilding()` is invoked by the button click, everything works as expected, both `Debug.Log()` calls print the correct `actionableModel`. However, when the method is invoked via the `Actionable` script, the second log `Debug.Log(this.actionableModel)` prints `null` (even though `this` object is still `Planet` for some reason). Since the first log `Debug.Log(planet.actionableModel)` still prints the correct value, I assume this is not a problem with the actual value of the property. (I have only a single “Planet” object)

From my experience outside C# and Unity, in which I have only humble experience, I would assume that the context here is improper and that I would need to pass it when I am invoking the method. There seems to be no way to do that though in `UnityEvent` object.

How can I invoke the `UnityEvent` callback in the same way as `Button` does, such that I have access to `actionableModel` in `stopBuilding`?

## c# – Unity – User Interface dragging problem with IDragHandler

In my inventory system I want that items can be dragged and dropped into inventory slots. I managed to make it work but only in a weird way. So when the player starts dragging it picks up the item and it follows the mouse’s position. When he realeses the button outside the inventory it’s position is restored to the slot where he picked it up from. The problem is that when he drops it on a possible inventory slot it does the same because the mouse is top on the item and the slot as well but the item is rendered above everything else. How can I make the dragging ignore the item itself?

Start dragging:

``````    public void OnBeginDrag(PointerEventData eventData)
{
GameObject draggedObject = eventData.rawPointerPress;
if(draggedObject.GetComponent<RectTransform>() is null) return;

if(draggedObject.tag == "InventoryItem")
{
Debug.Log("InventoryItem drag has started!");
dragStartSlot = draggedObject.transform.parent.gameObject;
draggedItem = draggedObject;
draggedItem.transform.SetParent(canvas.transform);
draggedItem.transform.SetAsLastSibling();

}
}
``````

End dragging:

``````    public void OnEndDrag(PointerEventData eventData)
{

GameObject mouseReleasedObject = eventData.pointerCurrentRaycast.gameObject;
if(draggedItem is null) return;
Debug.Log("Released at: "+mouseReleasedObject.gameObject.name);
if(mouseReleasedObject.transform.tag == "InventorySlot")
{
if(mouseReleasedObject.transform.childCount < 1)
{
//  the inventory slot is empty, we place here the item!
draggedItem.transform.SetParent(mouseReleasedObject.transform);
draggedItem.GetComponent<RectTransform>().localPosition = Vector3.zero;
}
else
{
//  the inventory slot is taken, we swap the items!
}
}
else
{
//  the item is not released on a proper slot, we restore it's position!
draggedItem.transform.SetParent(dragStartSlot.transform);
draggedItem.GetComponent<RectTransform>().localPosition = Vector3.zero;
}
}
``````

EDIT: Finally found a solution with the Canvas’ Graphic Raycaster Component. This is the solution if anyone interested:

``````public void OnEndDrag(PointerEventData eventData)
{

bool itemHasBeenPlaced = false;
var results = new List<RaycastResult>();
graphicRaycaster.Raycast(eventData, results);
foreach(var hit in results)
{
if(hit.gameObject.transform.tag == "InventorySlot")
{
if(hit.gameObject.transform.childCount < 1)
{
//  the inventory slot is empty, we place here the item!
draggedItem.transform.SetParent(hit.gameObject.transform);
draggedItem.GetComponent<RectTransform>().localPosition = Vector3.zero;
itemHasBeenPlaced = true;
}
else
{
//  TODO: the inventory slot is taken, we swap the items!
Debug.Log("the inventory slot is taken, we swap the items!");
itemHasBeenPlaced = true;
}
}
}
if(!itemHasBeenPlaced)
{
//  the item is not released on a proper slot, we restore it's position!
draggedItem.transform.SetParent(dragStartSlot.transform);
draggedItem.GetComponent<RectTransform>().localPosition = Vector3.zero;
}

}
$$```$$
``````

## particles – Where to place “Set XYZ over life” blocks in Unity VFX graph?

As the title says, I am learning VFX graph in Unity and I am curious where I should place `"Set ... over Life"`, for example `"Set Color over Life"` which adjust the color based on the particle’s age.

When we create a new visual effect graph, they are placed in the Output context by default, which kind of seems odd to me, since it seems more like a Update function?
It also works if I place it in the Update context, but I am afraid that I probably mess with the performance if the block should not be placed there for some reason.
Also, why can’t I set it in the Initialize context – if I do, no changes over time are applied.

Probably someone could point me to the right documentation or some explanation for this, thanks.
In general, it would be nice to have a documentation that states which blocks should be used within which context (Initialize, Update, Output).

## Unity App Crashes on Android

I’ve had this issue many a time, unfortunately anything I’ve used to fix it before doesn’t work. So, if I build and run the app, it will run the app for about 5 seconds, before crashing. If I install the apk and try and run it, it will crash immediately.

I cannot for the life of me figure out what’s wrong, this is an app I’ve built with no issues a hundred times, I am pretty certain I never changed any player settings since then, I did, however, reinstall the unity version as I had an issue with the android SDK because it didn’t install properly.

I ran logcat in the Android Studio, and the only errors of note I could find are invalid vkGetInstanceProcAdd and Connecting to host time out, player connection will be disabled?
However, it does seem to initialize the app through Android studio.

Here is a pastebin of my logcat, filtered to only include unity related issues.

https://pastebin.com/buRGfjXa

## unity – How can I make the transform to stop slowly smooth before the next waypoint?

You’re moving the object using `Vector3.Lerp()`. When you move with linear interpolation (lerp), the speed is constant. To add speed up at the beginning or slow down at the end, you’d need to use easing.

Ironically the source you obtained this code from seems to have left a comment referencing easing but then forgotten to actually include the easing section.

There are many ways to implement easing. One way is to use easing functions. You can search the web to find free libraries of easing functions for Unity. You’d generally use them something like this:

``````var t = passedTime / duration;
var lerpFactor = EasingLibrary.EaseInOutCubic(t);
transform.position = Vector3.Lerp(currentPosition, currentWaypoint.position, lerpFactor);
``````

Another solution is to use an Animation Curve. With this approach, you’d declare a curve field at the top of your script:

``````(SerializeField) private AnimationCurve easingCurve;
``````

This will show a curve field in the Inspector. We’ll use this curve to define the interpolated motion of our GameObject. Start with something like this (note that the curve should start at (0,0) and end at (1,1):

Then we’ll use the curve in our movement coroutine:

``````do {
var t = passedTime / duration;
var lerpFactor = easingCurve.Evaluate(t); //use the curve to apply easing
transform.position = Vector3.Lerp(currentPosition, currentWaypoint.position, lerpFactor);
passedTime += Time.deltaTime;
yield return null;
} while (passedTime <= duration);
``````

Our curve defines a function which takes an input and returns an output. The “time” (x-axis) of the curve represents the input (in our case, a time from 0 – 1) and the “value” (y-axis) represents the corresponding output (in our case, how far the GameObject has moved between the start and end positions).

If the curve was a perfectly straight line from (0,0) to (1,1) the output would be linear (in fact, it would be exactly the same value as the input). However, this s-shaped curve will ease the motion in at the beginning and ease it out at the end. The flatter the curve is in a particular area, the slower our motion will be at that time.

If you find this confusing, try messing around with the shape of the curve and study how this affects the animation.

Easing functions usually are easier to use. If there’s a specific style of easing that you want, you would just call the appropriate function. Animation curves take a little more work to set up but give you more control over the exact motion.

For a project which makes heavy use of easing, I’ll usually rely on an easing library and only use an animation curve if the easing functions don’t give me enough fine control. If I only need to use easing in one or two places, I’ll usually just use an animation curve rather than adding an easing library to the project.

## unity – How to get my specific Item index on inventory when pickup?

So I want to make some inventory system for my game, and I found some issue when collecting the item, what I want here matching the index `Inventory_UI system` exactly the same as `currentIndex` on the collected item, then display it on `Inventory_UI system`, let say I pickUp some item with the `currentIndex = 1` so on `Inventory_UI system` `index=1` too and so on. this happening when inventory description to so the `id` is same as `itemIndex` picked up.

## so here the the script:

• ItemManager( this for information of item ):
``````(System.Serializable)
public class theItems
{
public string Name;
public GameObject() allCurrentPrefabs;
public int numberOfIndex;
public AudioClip() allSound;
public string() terjemahannya;
public string() latinnya;
}

public class _ItemManager : MonoBehaviour
{
public static _ItemManager instance;

private void Awake()
{
instance = this;
}

public List<theItems> items;

public int Surah;

public AudioSource aSource;

// Start is called before the first frame update
void Start()
{

}

// Update is called once per frame
void Update()
{

}

public void PlaySurah(int surahnya, int ayatnya)
{
aSource.clip = items(surahnya).allSurahSound(ayatnya);
aSource.Play();
}
}
``````
• CollectibleItem ( this attach to each item )
`````` public static _CollectibleAyat instance;

private void Awake()
{
instance = this;
}

public enum InteractionType
{
none, pickUp, Examine
}

public InteractionType interactType;

public int currentIndex;

public string terjemahannya;
public string latinnya;
public GameObject allCurrentPrefabs;

public UnityEvent customevent;

public void Reset()
{
GetComponent<Collider2D>().isTrigger = true;
}

public void interact()
{
switch (interactType)
{
//case InteractionType.none:
//    Debug.Log("None");
//    break;
case InteractionType.Examine:

_InteractSystem.instance.Examine(this);

Debug.Log("Examine");

break;
case InteractionType.pickUp:
// Add the object to the pickUpItems List
// Delete the Object

_InventorySystem.instance.PickUpItem(gameObject);
gameObject.SetActive(false);

Debug.Log("PickingUp");
break;
default:

Debug.Log("Null Item");
break;
}

//Invoke (Call) the custom Event(s)
customevent.Invoke();
}
``````
• This InventorySystem( when item pickup)
``````public static _InventorySystem instance;

private void Awake()
{
instance = this;
}

public List<GameObject> items = new List<GameObject>();
public bool isOpen;
public int ayah;

public GameObject UI_InventoryWindow;
public Image() item_Images;

// Start is called before the first frame update
void Start()
{

}

// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.I))
{
ToggleInventory();
}
}

public void ToggleInventory()
{
isOpen = !isOpen;
UI_InventoryWindow.SetActive(isOpen);
}

public void PickUpItem(GameObject item)
{
Update_UI();
}

public void Update_UI()
{
HideAll();

for (int i = 0; i < items.Count; i++)
{
item_Images(i).sprite = items(i).GetComponent<SpriteRenderer>().sprite;
item_Images(i).gameObject.SetActive(true);

}

}

public void HideAll()
{
foreach (var i in item_Images)
{
i.gameObject.SetActive(false);
}
}

//SampeSini
public void ShowDescription(int id)
{

}

public void HideDescription()
{

}
``````

note: on the `ShowDescription(int id)` i want to show item information what same as i picked up i have mentioned it above.

## unity – SpriteRenderer color not responding to script!

I have written a simple c# class that is supposed to change the color of the Player Renderer.
But, there seems to be a problem! whenever I call the function OnCallFun() … the color stays put and does not change.
I have looked into the solution for quite some time now but no hope.
does anyone have a solution?