# Question
Title: Trying to define a custom Composite to the new Unity Input System but failing somewhere
I'm following the "Touch Samples" sample project that comes with the "input system" package.

In one of the sample scene, there is a script that defines a custom composite Binding (for example the 2D vector composite).

I'm practically rewriting the same scripts except changing some inputs to be added to the composite, but it's throwing me these errors, and since I'm relatively new to writing code don't know how to begin solving the issue. The manual and the scripting API are no help either.

these are the errors

this is the example Script that adds a custom composite.

```

using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Layouts;
using UnityEngine.InputSystem.Utilities;
#if UNITY_EDITOR
using UnityEditor;
#endif

namespace InputSamples.Drawing
{
    /// <summary>
    /// Simple object to contain information for drag inputs.
    /// </summary>
    public struct PointerInput
    {

        public bool Contact;

        /// <summary>
        /// ID of input type.
        /// </summary>
        public int InputId;

        /// <summary>
        /// Position of draw input.
        /// </summary>
        public Vector2 Position;

        /// <summary>
        /// Orientation of draw input pen.
        /// </summary>
        public Vector2? Tilt;

        /// <summary>
        /// Pressure of draw input.
        /// </summary>
        public float? Pressure;

        /// <summary>
        /// Radius of draw input.
        /// </summary>
        public Vector2? Radius;

        /// <summary>
        /// Twist of draw input.
        /// </summary>
        public float? Twist;
    }

    // What we do in PointerInputManager is to simply create a separate action for each input we need for PointerInput.
    // This here shows a possible alternative that sources all inputs as a single value using a composite. Has pros
    // and cons. Biggest pro is that all the controls actuate together and deliver one input value.
    //
    // NOTE: In PointerControls, we are binding mouse and pen separately from touch. If we didn't care about multitouch,
    //       we wouldn't have to to that but could rather just bind `<Pointer>/position` etc. However, to source each touch
    //       as its own separate PointerInput source, we need to have multiple PointerInputComposites.
    #if UNITY_EDITOR
    [InitializeOnLoad]
    #endif
    public class PointerInputComposite : InputBindingComposite<PointerInput>
    {
        [InputControl(layout = "Button")]
        public int contact;

        [InputControl(layout = "Vector2")]
        public int position;

        [InputControl(layout = "Vector2")]
        public int tilt;

        [InputControl(layout = "Vector2")]
        public int radius;

        [InputControl(layout = "Axis")]
        public int pressure;

        [InputControl(layout = "Axis")]
        public int twist;

        [InputControl(layout = "Integer")]
        public int inputId;

        public override PointerInput ReadValue(ref InputBindingCompositeContext context)
        {
            var contact = context.ReadValueAsButton(this.contact);
            var pointerId = context.ReadValue<int>(inputId);
            var pressure = context.ReadValue<float>(this.pressure);
            var radius = context.ReadValue<Vector2, Vector2MagnitudeComparer>(this.radius);
            var tilt = context.ReadValue<Vector2, Vector2MagnitudeComparer>(this.tilt);
            var position = context.ReadValue<Vector2, Vector2MagnitudeComparer>(this.position);
            var twist = context.ReadValue<float>(this.twist);

            return new PointerInput
            {
                Contact = contact,
                InputId = pointerId,
                Position = position,
                Tilt = tilt != default ? tilt : (Vector2?)null,
                Pressure = pressure > 0 ? pressure : (float?)null,
                Radius = radius.sqrMagnitude > 0 ? radius : (Vector2?)null,
                Twist = twist > 0 ? twist : (float?)null,
            };
        }

        #if UNITY_EDITOR
        static PointerInputComposite()
        {
            Register();
        }

        #endif

        [RuntimeInitializeOnLoadMethod]
        private static void Register()
        {
            InputSystem.RegisterBindingComposite<PointerInputComposite>();
        }
    }
}

```

and this is my code for my custom composite:

```

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.InputSystem.Utilities;
using UnityEngine.InputSystem.Layouts;
#if UNITY_EDITOR
using UnityEditor;
#endif

public struct myPointerInput
{
    public bool Press;
    public int PressCount;
    public Vector2 Position;
    public Vector2 Delta;
    public Vector2? Radius;

    //touch specific
    public bool? Tap;
    //public UnityEngine.InputSystem.TouchPhase? phase;
    public Vector2? StartPosition;
    public float? StartTime;

    //mouse Specific
    public Vector2? Scroll;
}

#if UNITY_EDITOR
[InitializeOnLoad]
#endif
public class MyPointerInput : InputBindingComposite<myPointerInput>
{
    [InputControl(layout = "Button")]
    public int press;
    [InputControl(layout = "Integer")]
    public int pressCount;
    [InputControl(layout = "Vector2")]
    public int position;
    [InputControl(layout = "Vector2")]
    public int delta;
    [InputControl(layout = "Vector2")]
    public int radius;

    //touch specific
    [InputControl(layout = "Button")]
    public int tap;
    //[InputControl(layout = "TouchPhase")]
    //public UnityEngine.InputSystem.TouchPhase phase;
    [InputControl(layout = "Vector2")]
    public int startPosition;
    [InputControl(layout = "Double")]
    public int startTime;

    //mouse Specific
    [InputControl(layout = "Vector2")]
    public int scroll;

    public override myPointerInput ReadValue(ref InputBindingCompositeContext context)
    {
        var press = context.ReadValueAsButton(this.press);
        var pressCount = context.ReadValue<int>(this.pressCount);
        var position = context.ReadValue<Vector2, Vector2MagnitudeComparer>(this.position);
        var delta = context.ReadValue<Vector2, Vector2MagnitudeComparer>(this.delta);
        var radius = context.ReadValue<Vector2, Vector2MagnitudeComparer>(this.radius);

        var tap = context.ReadValueAsButton(this.tap);
        //var phase = context.ReadValue<UnityEngine.InputSystem.TouchPhase>(this.phase);
        var startPosition = context.ReadValue<Vector2, Vector2MagnitudeComparer>(this.startPosition);
        var startTime = context.ReadValue<float>(this.startTime);

        var scroll = context.ReadValue<Vector2, Vector2MagnitudeComparer>(this.scroll);

        return new myPointerInput
        {
            Press = press,
            PressCount = pressCount,
            Position = position,
            Delta = delta,
            Radius = radius.sqrMagnitude > 0 ? radius : (Vector2?)null,
            //Tap = tap,
            StartPosition = startPosition,
            StartTime = startTime,
            Scroll = scroll
        };
    }

#if UNITY_EDITOR
    static MyPointerInput()
    {
        Register();
    }
#endif

    [RuntimeInitializeOnLoadMethod]
    private static void Register()
    {
        InputSystem.RegisterBindingComposite<myPointerInput>();
    }

}

```

these are the errors in Text form:

```
ArgumentException: Don't know how to convert PrimitiveValue to 'Object'
Parameter name: type
UnityEngine.InputSystem.Utilities.PrimitiveValue.ConvertTo (System.TypeCode type) (at Library/PackageCache/com.unity.inputsystem@1.0.0/InputSystem/Utilities/PrimitiveValue.cs:227)
UnityEngine.InputSystem.Utilities.NamedValue.ConvertTo (System.TypeCode type) (at Library/PackageCache/com.unity.inputsystem@1.0.0/InputSystem/Utilities/NamedValue.cs:28)
UnityEngine.InputSystem.Editor.Lists.ParameterListView.Initialize (System.Type registeredType, UnityEngine.InputSystem.Utilities.ReadOnlyArray`1[TValue] existingParameters) (at Library/PackageCache/com.unity.inputsystem@1.0.0/InputSystem/Editor/AssetEditor/ParameterListView.cs:146)
UnityEngine.InputSystem.Editor.InputBindingPropertiesView.InitializeCompositeProperties () (at Library/PackageCache/com.unity.inputsystem@1.0.0/InputSystem/Editor/AssetEditor/InputBindingPropertiesView.cs:194)
UnityEngine.InputSystem.Editor.InputBindingPropertiesView.DrawGeneralProperties () (at Library/PackageCache/com.unity.inputsystem@1.0.0/InputSystem/Editor/AssetEditor/InputBindingPropertiesView.cs:69)
UnityEngine.InputSystem.Editor.PropertiesViewBase.DrawGeneralGroup () (at Library/PackageCache/com.unity.inputsystem@1.0.0/InputSystem/Editor/AssetEditor/PropertiesViewBase.cs:59)
UnityEngine.InputSystem.Editor.PropertiesViewBase.OnGUI () (at Library/PackageCache/com.unity.inputsystem@1.0.0/InputSystem/Editor/AssetEditor/PropertiesViewBase.cs:39)
UnityEngine.InputSystem.Editor.InputActionEditorWindow.DrawPropertiesColumn (System.Single width) (at Library/PackageCache/com.unity.inputsystem@1.0.0/InputSystem/Editor/AssetEditor/InputActionEditorWindow.cs:699)
UnityEngine.InputSystem.Editor.InputActionEditorWindow.OnGUI () (at Library/PackageCache/com.unity.inputsystem@1.0.0/InputSystem/Editor/AssetEditor/InputActionEditorWindow.cs:637)
System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) (at <437ba245d8404784b9fbab9b439ac908>:0)
Rethrow as TargetInvocationException: Exception has been thrown by the target of an invocation.
System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) (at <437ba245d8404784b9fbab9b439ac908>:0)
System.Reflection.MethodBase.Invoke (System.Object obj, System.Object[] parameters) (at <437ba245d8404784b9fbab9b439ac908>:0)
UnityEditor.HostView.Invoke (System.String methodName, System.Object obj) (at <78f1ad0f25c84e3ca853e639f50d95f5>:0)
UnityEditor.HostView.Invoke (System.String methodName) (at <78f1ad0f25c84e3ca853e639f50d95f5>:0)
UnityEditor.HostView.InvokeOnGUI (UnityEngine.Rect onGUIPosition, UnityEngine.Rect viewRect) (at <78f1ad0f25c84e3ca853e639f50d95f5>:0)
UnityEditor.DockArea.DrawView (UnityEngine.Rect viewRect, UnityEngine.Rect dockAreaRect) (at <78f1ad0f25c84e3ca853e639f50d95f5>:0)
UnityEditor.DockArea.OldOnGUI () (at <78f1ad0f25c84e3ca853e639f50d95f5>:0)
UnityEngine.UIElements.IMGUIContainer.DoOnGUI (UnityEngine.Event evt, UnityEngine.Matrix4x4 parentTransform, UnityEngine.Rect clippingRect, System.Boolean isComputingLayout, UnityEngine.Rect layoutSize, System.Action onGUIHandler, System.Boolean canAffectFocus) (at <3736d7cfd1f845a5922f99478cb469e7>:0)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)

```

```
GUI Error: You are pushing more GUIClips than you are popping. Make sure they are balanced.
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)

```

```
  ArgumentException: Getting control 1's position in a group with only 1 controls when doing repaint
Aborting
UnityEngine.GUILayoutGroup.GetNext () (at <817eebdd70f8402280b9cb11fff8b976>:0)
UnityEngine.GUILayoutUtility.DoGetRect (System.Single minWidth, System.Single maxWidth, System.Single minHeight, System.Single maxHeight, UnityEngine.GUIStyle style, UnityEngine.GUILayoutOption[] options) (at <817eebdd70f8402280b9cb11fff8b976>:0)
UnityEngine.GUILayoutUtility.GetRect (System.Single minWidth, System.Single maxWidth, System.Single minHeight, System.Single maxHeight, UnityEngine.GUIStyle style, UnityEngine.GUILayoutOption[] options) (at <817eebdd70f8402280b9cb11fff8b976>:0)
UnityEditor.EditorGUILayout.GetControlRect (System.Boolean hasLabel, System.Single height, UnityEngine.GUIStyle style, UnityEngine.GUILayoutOption[] options) (at <78f1ad0f25c84e3ca853e639f50d95f5>:0)
UnityEditor.EditorGUILayout.Popup (UnityEngine.GUIContent label, System.Int32 selectedIndex, UnityEngine.GUIContent[] displayedOptions, UnityEngine.GUIStyle style, UnityEngine.GUILayoutOption[] options) (at <78f1ad0f25c84e3ca853e639f50d95f5>:0)
UnityEditor.EditorGUILayout.Popup (UnityEngine.GUIContent label, System.Int32 selectedIndex, UnityEngine.GUIContent[] displayedOptions, UnityEngine.GUILayoutOption[] options) (at <78f1ad0f25c84e3ca853e639f50d95f5>:0)
UnityEngine.InputSystem.Editor.InputBindingPropertiesView.DrawGeneralProperties () (at Library/PackageCache/com.unity.inputsystem@1.0.0/InputSystem/Editor/AssetEditor/InputBindingPropertiesView.cs:72)
UnityEngine.InputSystem.Editor.PropertiesViewBase.DrawGeneralGroup () (at Library/PackageCache/com.unity.inputsystem@1.0.0/InputSystem/Editor/AssetEditor/PropertiesViewBase.cs:59)
UnityEngine.InputSystem.Editor.PropertiesViewBase.OnGUI () (at Library/PackageCache/com.unity.inputsystem@1.0.0/InputSystem/Editor/AssetEditor/PropertiesViewBase.cs:39)
UnityEngine.InputSystem.Editor.InputActionEditorWindow.DrawPropertiesColumn (System.Single width) (at Library/PackageCache/com.unity.inputsystem@1.0.0/InputSystem/Editor/AssetEditor/InputActionEditorWindow.cs:699)
UnityEngine.InputSystem.Editor.InputActionEditorWindow.OnGUI () (at Library/PackageCache/com.unity.inputsystem@1.0.0/InputSystem/Editor/AssetEditor/InputActionEditorWindow.cs:637)
System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) (at <437ba245d8404784b9fbab9b439ac908>:0)
Rethrow as TargetInvocationException: Exception has been thrown by the target of an invocation.
System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) (at <437ba245d8404784b9fbab9b439ac908>:0)
System.Reflection.MethodBase.Invoke (System.Object obj, System.Object[] parameters) (at <437ba245d8404784b9fbab9b439ac908>:0)
UnityEditor.HostView.Invoke (System.String methodName, System.Object obj) (at <78f1ad0f25c84e3ca853e639f50d95f5>:0)
UnityEditor.HostView.Invoke (System.String methodName) (at <78f1ad0f25c84e3ca853e639f50d95f5>:0)
UnityEditor.HostView.InvokeOnGUI (UnityEngine.Rect onGUIPosition, UnityEngine.Rect viewRect) (at <78f1ad0f25c84e3ca853e639f50d95f5>:0)
UnityEditor.DockArea.DrawView (UnityEngine.Rect viewRect, UnityEngine.Rect dockAreaRect) (at <78f1ad0f25c84e3ca853e639f50d95f5>:0)
UnityEditor.DockArea.OldOnGUI () (at <78f1ad0f25c84e3ca853e639f50d95f5>:0)
UnityEngine.UIElements.IMGUIContainer.DoOnGUI (UnityEngine.Event evt, UnityEngine.Matrix4x4 parentTransform, UnityEngine.Rect clippingRect, System.Boolean isComputingLayout, UnityEngine.Rect layoutSize, System.Action onGUIHandler, System.Boolean canAffectFocus) (at <3736d7cfd1f845a5922f99478cb469e7>:0)
UnityEngine.UIElements.IMGUIContainer.HandleIMGUIEvent (UnityEngine.Event e, UnityEngine.Matrix4x4 worldTransform, UnityEngine.Rect clippingRect, System.Action onGUIHandler, System.Boolean canAffectFocus) (at <3736d7cfd1f845a5922f99478cb469e7>:0)
UnityEngine.UIElements.IMGUIContainer.DoIMGUIRepaint () (at <3736d7cfd1f845a5922f99478cb469e7>:0)
UnityEngine.UIElements.UIR.RenderChainCommand.ExecuteNonDrawMesh (UnityEngine.UIElements.UIR.DrawParams drawParams, System.Boolean straightY, System.Single pixelsPerPoint, System.Exception& immediateException) (at <3736d7cfd1f845a5922f99478cb469e7>:0)
Rethrow as ImmediateModeException
UnityEngine.UIElements.UIR.RenderChain.Render (UnityEngine.Rect viewport, UnityEngine.Matrix4x4 projection, UnityEngine.UIElements.PanelClearFlags clearFlags) (at <3736d7cfd1f845a5922f99478cb469e7>:0)
UnityEngine.UIElements.UIRRepaintUpdater.DrawChain (UnityEngine.Rect viewport, UnityEngine.Matrix4x4 projection) (at <3736d7cfd1f845a5922f99478cb469e7>:0)
UnityEngine.UIElements.UIRRepaintUpdater.Update () (at <3736d7cfd1f845a5922f99478cb469e7>:0)
UnityEngine.UIElements.VisualTreeUpdater.UpdateVisualTreePhase (UnityEngine.UIElements.VisualTreeUpdatePhase phase) (at <3736d7cfd1f845a5922f99478cb469e7>:0)
UnityEngine.UIElements.Panel.UpdateForRepaint () (at <3736d7cfd1f845a5922f99478cb469e7>:0)
UnityEngine.UIElements.Panel.Repaint (UnityEngine.Event e) (at <3736d7cfd1f845a5922f99478cb469e7>:0)
UnityEngine.UIElements.UIElementsUtility.DoDispatch (UnityEngine.UIElements.BaseVisualElementPanel panel) (at <3736d7cfd1f845a5922f99478cb469e7>:0)
UnityEngine.UIElements.UIElementsUtility.ProcessEvent (System.Int32 instanceID, System.IntPtr nativeEventPtr) (at <3736d7cfd1f845a5922f99478cb469e7>:0)
UnityEngine.GUIUtility.ProcessEvent (System.Int32 instanceID, System.IntPtr nativeEventPtr) (at <817eebdd70f8402280b9cb11fff8b976>:0)

```

# Answer
> 0 votes
I still don't know what's wrong with my script, but I wrote a identical one in another project and it worked like a charm.

Here is the new script:

```
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Utilities;
using UnityEngine.InputSystem.Layouts;
#if UNITY_EDITOR
using UnityEditor;
#endif

public struct myCompositData
{
    public bool Press;
    public int PressCount;
    public Vector2 Position;
    public Vector2 Delta;
    public Vector2 Radius;

    public bool Tap;
    //public UnityEngine.InputSystem.TouchPhase Phase;
    public Vector2 StartPosition;
    public double StartTime;

    public Vector2 Scroll;
}

#if UNITY_EDITOR
[InitializeOnLoad]
#endif
public class myComposit : InputBindingComposite<myCompositData>
{

#if UNITY_EDITOR
    static myComposit()
    {
        Initialize();
    }
#endif

    [RuntimeInitializeOnLoadMethod]
    private static void Initialize()
    {
        InputSystem.RegisterBindingComposite<myComposit>();
    }

    [InputControl(layout = "Button")]
    public int press;
    [InputControl(layout = "Integer")]
    public int pressCount;
    [InputControl(layout = "Vector2")]
    public int position;
    [InputControl(layout = "Vector2")]
    public int delta;
    [InputControl(layout = "Vector2")]
    public int radius;

    [InputControl(layout = "Button")]
    public int tap;
    //[InputControl(layout = "TouchPhase")]
    //public int phase;
    [InputControl(layout = "Vector2")]
    public int startPosition;
    [InputControl(layout = "Double")]
    public int startTime;

    [InputControl(layout = "Vector2")]
    public int scroll;

    public override myCompositData ReadValue(ref InputBindingCompositeContext context)
    {

        var press = context.ReadValueAsButton(this.press);
        var pressCount = context.ReadValue<int>(this.pressCount);
        var position = context.ReadValue<Vector2, Vector2MagnitudeComparer>(this.position);
        var delta = context.ReadValue<Vector2, Vector2MagnitudeComparer>(this.delta);
        var radius = context.ReadValue<Vector2, Vector2MagnitudeComparer>(this.radius);

        var tap = context.ReadValueAsButton(this.tap);
        //var phase = context.ReadValue<UnityEngine.InputSystem.TouchPhase>(this.phase);
        var startPosition = context.ReadValue<Vector2, Vector2MagnitudeComparer>(this.startPosition);
        var startTime = context.ReadValue<double>(this.startTime);

        var scroll = context.ReadValue<Vector2, Vector2MagnitudeComparer>(this.scroll);

        return new myCompositData()
        {
            Press = press,
            PressCount = pressCount,
            Position = position,
            Delta = delta,
            Radius = radius,

            Tap = tap,
            StartPosition = startPosition,
            StartTime = startTime,

            Scroll = scroll

        };
    }
}

```

If anyone could compare the two scripts and determine what I did wrong that would be great.

---
Tags: unity, input
---


title: Open sourcing a Unity game with assets

text:
# Question
Title: Open sourcing a Unity game with assets
So, I have a goal to make and publish one (small, stupid, simple) game every ~Saturday. (I've made two, so far, thanks for asking.) I've started in Unity, because it's convenient. My plan for each game was to have a free version with ads, a paid version without, but *also* have it open sourced (and if they're willing to go to the trouble of removing the ads themselves, so be it).

Now, concurrently, I keep wandering into e.g. Humble Bundle, or Unity Asset Store sales, and picking up things I probably don't need but maybe might use.

It has just occurred to me, though, that if I'm open sourcing these games - I kinda suspect the owners of these assets aren't going to be happy with me just posting all their files on the internet. Pretty sure I can't open source assets I've purchased.

Now, I could probably just use free assets and make note of where they came from, and everyone would PROBABLY be ok with that. But that significantly restricts the things I can use. (And it would be kindof a waste - you don't want to know how many ancient untouched game-dev Humble Bundles I'm sitting on, haha.)

Is there some kind of workaround? Like, if I posted the whole project, but included a license stating that only my code was open sourced, and the rest could not be used in anything else, for instance? Anybody know any nice solutions?

# Answer
> 3 votes
Unfortunately, there's no real workaround other than contacting the owners of the products you licensed whose license doesn't already specify they can be freely distributed. Even if in YOUR license it says that they're not allowed to touch that stuff, you're still distributing other pieces of software without being allowed to.

There is one solution which would save you a lot of time and would also make it harder for people to just copy your game outright. Put all the purchased and downloaded assets and the like in a separate folder in your project, then when it's time to upload your project to wherever you're hosting the source (I'm assuming GitHub?) just exclude that folder. If you still want to make it easy for others to figure out, just post a list of all dependencies in your readme. Or write a bit of code that does that for you.

Good luck!

---
Tags: unity, assets, open-source
---


title: Angle object only in the X axis

text:
# Question
Title: Angle object only in the X axis
I'm trying to code a turret to angle towards a target, where I have one part of the turret only rotating on the left/right, and I want to animate another part to only angle up/down. I've got the left/right (`RotateTowardsTarget`) working, but I can't get the up/down (`AngleTowardsTarget`) to work, it seems to also rotate the object as well as angle it.

`turretXRotation` is a child of `turretYRotation`. These objects form the top of a gun turret, so the base will rotate, and the gun barrel will angle towards the target

```
/// <summary>
/// Orient the turret weapon towards the target.
/// </summary>
/// <param name="lookPosition"></param>
private void OrientWeaponsTowards(Vector3 lookPosition)
{
    RotateTowardsTarget(lookPosition);
    AngleTowardsTarget(lookPosition);
}

/// <summary>
/// Rotate towards the target.
/// </summary>
/// <param name="lookPosition"></param>
private void RotateTowardsTarget(Vector3 lookPosition)
{
    // Determine which direction to rotate towards
    Vector3 targetDirection = lookPosition - transform.position;

    // The step size is equal to speed times frame time.
    float singleStep = weaponRotationSpeed * Time.deltaTime;

    // Rotate the forward vector towards the target direction by one step
    Vector3 newDirection = Vector3.RotateTowards(
        turretYRotation.transform.forward,
        targetDirection,
        singleStep,
        0.0f
    );

    // Draw a ray pointing at our target in
    //Debug.DrawRay(turretYRotation.transform.position, newDirection, Color.red, 3);

    newDirection.y = 0;
    // Calculate a rotation a step closer to the target and applies rotation to this object
    turretYRotation.transform.rotation = Quaternion.LookRotation(newDirection);
}

/// <summary>
/// Angle towards the target.
/// </summary>
/// <param name="lookPosition"></param>
private void AngleTowardsTarget(Vector3 lookPosition)
{
    // Determine which direction to rotate towards
    Vector3 targetDirection = lookPosition - turretXRotation.transform.position;

    // The step size is equal to speed times frame time.
    float singleStep = weaponRotationSpeed * Time.deltaTime;

    // Rotate the forward vector towards the target direction by one step
    Vector3 newDirection = Vector3.RotateTowards(
        turretXRotation.transform.forward,
        targetDirection,
        singleStep,
        0.0f
    );

    // Draw a ray pointing at our target in
    //Debug.DrawRay(turretXRotation.transform.position, newDirection, Color.red, 3);

    // Calculate a rotation a step closer to the target and applies rotation to this object
    turretXRotation.transform.rotation = Quaternion.LookRotation(newDirection);
}

Does anyone know how I can just make the `turretXRotation` only change it's X value to aim towards the target? I've tried similar stuff to the rotating, by zeroing out some of the x/y/z coords, but I can't seem to crack it.

```

# Answer
> 0 votes
OK, this answer may sound a bit weird, but from what you've posted it looks like you're aiming the two parts separately at the same thing. So right now the gun barrel is probably rotating very weirdly, but is in the end still looking at the target as intended.

Now the bottom part of the turret is working fine, which makes sense, since that part just looks at the target normally, but ignores any vertical rotation. However, what you really should be doing when aiming the barrel, is aiming it as if the bottom part were already rotated correctly and facing the target.

## Solution 1:

The fix would be to do this:

```
Vector3 look = Quaternion.LookRotation(newDirection).eulerAngles;
turretXRotation.transform.localRotation = Quaternion.Euler(look.x, 0, 0);

```

## Solution 2:

A really easy but quite hacky way to do it would be to create an invisible game object inside the turret that tracks the target 1 to 1, then have the segments of the turret rotate towards those rotation values. That way you leave all the hard stuff for Unity to figure out.

---
Tags: unity, c#, rotation, vector
---


# Question
Title: What is the difference between "offline" and "real time" rendering?
I have a rough idea: real-time is approximated with little or no global illumination. But how would you otherwise explain why offline rending takes so much longer? You hear things like "number of passes," et cetera...

Can you explain the difference in simple terms?

# Answer
> 9 votes
There is no inherit reason why offline rendering takes longer than real-time rendering.

It is just that when you render offline, the rendering process is usually much less performance-critical, so you have the option to use very expensive rendering techniques which would be too slow for real-time rendering. When you are free from the constraint that each frame must render in less than 20ms, you can use a lot more complex geometries with a lot more expensive rendering techniques.

Which techniques exactly are used for each scenario differs. Global illumination, for example, is often too slow for real-time rendering, but not always. When the geometry of the scene is simple enough, it can be pulled off in real-time. And while offline-rendering can use global illumination, it doesn't have to.

There are countless other rendering techniques which are more or less performant and give more or less beautiful results depending on the exact scene geometry. Depending on the circumstances, almost any rendering technique can be used both for real-time and offline rendering.

Raytracing, for example, is usually considered too slow for real-time rendering. But when you have a scene which only consists of perfect spheres, any polygon-based renderer would cry in despair while a raytracing engine can do this in real-time.

# Answer
> 2 votes
"Real-time rendering" is calculated at the instant you ask for your whatever solution to generate the images (different technologies are used to achieve this target). "Off-line" rendering is not necessarily the contrary of "real-time". The term is often used when speaking about configurators and especially web-configurators. Sometimes people also use the term "pre-calculated".

"Off-line rendering" is not submitted to the time constraint. Basically a scene is prepared and then a series of pictures is generated ("pre-calculated") and ultimately assembled into a sort of a video clip that then is viewed ("off line"). The choice of type of technology used ("real time rendering" or "ray-tracing") depends on secondary criteria (complexity and type of geometries and materials to be rendered). There are excellent software packages for both technologies out there.

Where "ray tracing" is often claimed to be "physically correct", "real-time rendering" uses various "tricks" to generate images that appear to your eye (and more importantly to your brain) like real, "photorealistic".

Thus said, the fact that you need calculating images in less than 20ms eliminates many solutions because of this time constraint. Two typical examples here are "immersive solutions" (like CAVE systems) or "web-configurators" high combinatory, impossible to pre-calculate. In both cases there is no way to predict the image required by the end-user. And pre-calculating all different possibilities would simply require too much time (often years, even at a speed of 20 ms per image).

# Answer
> 1 votes
The key difference between realtime and offline rendering is how much of a time budget you have to render a frame.

A realtime rendering situation needs to get everything done in a fraction of a second so it can keep up with user input (if there is any (eg. Demoscene productions are real-time rendered but rarely interactive)). If 25fps is the minimum to be considered playable, then that gives you 40ms to get everything done. Input processing, simulation state updates, mixing audio, drawing the frame, and putting it on screen.

Offline rendering can take as long as you like per frame (limited only by your patience), as it doesn't need to keep up with any inputs. It just takes a file as input and produces a file as output. Big budget films can take the better part of a day to render a single frame.

The tight time constraints of realtime rendering pose similarly tight limits on the complexity of what can be rendered. What kind of complexity you decide to favour is up to you, but there will be a trade-off to make between complexity of rendering method vs the complexity of the scene's construction. You can spend just as much processing power on a hundred-million-polygon CAD model with simple shading as you do on a near-photorealistic game with only a hundred-thousand polygons on screen. Oh, and the bloke using the CAD software will probably be more forgiving if the framerate drops a bit than the one playing the game.

# Answer
> 0 votes
Its just that when you view the animation, if your PC is powerfull enough to compute all the casts, shadows, textures, everything and etcetera, you are looking a live rendered view... but if you got some drops on the FrameRate, you shoud use the offline rendering which is the exact same of the other but, this will take the CPU to the limit because obviously it will try to render it as fast as it cans but obviously cant do it in real time, so this process will save each frame in a buffer (or a file) (like PRE-RENDER) when each frame has rendered completely, this way you can see everything rendered at full detail but when the process of rendering each frame has finnished...

---
Tags: graphics, rendering, global-illumination
---


# Question
Title: collision detection and normals from rigidbody
Until now I've been developing my player character using a Character Controller, but have since decided to switch to rigidbody due to the controller's limitations. In order for my movement code to run as expected I need to know when the player is colliding with anything, and the normal of the surface it's colliding with. This is easy with a Character Controller, but is there a simple way to do it with a rigidbody?

Here is a stripped down version of the script I'm using for collisions.

```
 // Used in other scripts (Necessary)
    public GameObject ground = null;
    public Vector3 groundNormal;
    public bool onGround;

    // Used internally
    public bool isColliding;
    public float slopeLimit;

    // Character Controller
    public CharacterController controller;

    void Start()
    {
        controller = GetComponent<CharacterController>();
    }

    void Update()
    {
        // Check if the player is colliding with anything (Character Controller)
        if (controller.collisionFlags == CollisionFlags.None)
        {
            isColliding = false;
        }
        else
        {
            isColliding = true;
        }

        // Check if the player is standing on the ground
        if (isColliding && groundNormal != Vector3.zero)
        {
            onGround = true;
        }
        else
        {
            onGround = false;
        }
    }

    void OnControllerColliderHit(ControllerColliderHit hit)
    {
        // Check for floor
        if (Vector3.Angle(transform.up, hit.normal) <= slopeLimit)
        {
            // Store floor object data
            ground = hit.gameObject;
            // Store ground surface normal
            groundNormal = Vector3.Normalize(hit.normal);
        }
        else
        {
            // reset variables
            ground = null;
            groundNormal = Vector3.zero;
        }
    }

```

`slopeLimit` is a static value. Additionally, getting the ground object isn't actually necessary atm, but I plan on using it later.

Edit: Currently I'm using `controller.collisionFlags` to detect when the player is colliding with something and haven't been able to find a similar alternative. Setting the `isColliding` bool to true using `Rigidbody.OnCollisionStay` would be simple, but setting it to false without use of another void function seems difficult. is that possible at all?

# Answer
> 0 votes
You can get your is-colliding boolean just by counting collisions entered and exited:

```
int _collisionCount;
public bool IsColliding { get { return _collisionCount > 0; } }

void OnCollisionEnter(Collision collision) {
    _collisionCount++;
}

void OnCollisionExit(Collision collision) {
    _collisionCount--;
}

```

There are lots of solutions to ground checks, but here's one I like to use:

```
public LayerMask groundLayers; // Populate this with which physics layers count as "ground".

bool IsOnGround(out Vector3 groundNormal) {
    groundNormal = Vector3.zero;

    if ( !IsColliding ) return false; // If we're not colliding with anything, we're not grounded.

    // Physics "contacts" can actually have some minor separation, so let's add a margin.
    float margin = Physics.defaultContactOffset;

    // Start your check from a little above the bottom of your capsule.
    // I like to set up my colliders so "foot position" is always transform.position,
    // but your setup may vary. I like to make my ground check radius 1 margin smaller
    // than my capsule radius, to make sure my check never starts already in-contact
    // with an obstacle.
    Vector3 checkOrigin = GetFootPosition()
                        + new Vector3(0, groundCheckRadius + margin, 0);

    // Check for a collision under our feet.
    if ( Physics.SphereCast(
             checkOrigin,        // Start just above the bottom of our capsule,
             groundCheckRadius,  // with a sphere slightly smaller than our capsule.
             Vector3.down,       // Fire it downwards,
             out RaycastHit hit, // and record what it hits,
             2 * margin,         // going just far enough to catch a touching contact,
             groundLayers        // with anything marked "ground".
    ) == false) return false;    // If we didn't hit anything, we're not grounded.

    if ( Vector3.Angle(transform.up, hit.normal) > slopeLimit)
        return false; // Too steep to stand on!

    // Otherwise, we are grounded. Extract the ground normal and return true.
    groundNormal = hit.normal;
    return true;
}

```

---
Tags: unity, collision-detection, rigidbody, normals
---


# Question
Title: How can I create a persistent seed for each chunk of an infinite procedural world?
I'm coding a chunk-based 2D game.

I generate chunks as the player explores the world. Chunks follow a procedural generation algorithm (with only one biome implemented at the minute, but I'll introduce more).

When the player leaves a chunk however and it's unloaded, that chunk is lost for good (unless they modified the chunk; if that is the case, I save it). This is because with each new chunk I generate, I generate a new random seed for it.

I introduced a *world seed* into my world. My chunks also have 'world coordinates', ie the first chunk you spawn in is at (0, 0) and the chunk to the right is at (1, 0), etc, in world coordinates.

I was thinking about ways I can combine the world coordinates and world seed in order to obtain a chunk seed. That way, since I *always know* the world seed and *always know* the world coordinates, I could obtain the same chunk seed in order to make sure the same chunk comes back after the player leaves it (and the chunk is unloaded) and then returns to that location in the world when it has to be reloaded.

Some of the ways I thought of were as follows:

* Use a simple equation like `abs(world seed * world_coordinate_x * world_coordinate_y)` where the absolute value function enforces a postive chunk seed.

This would not be an acceptable equation to use as the equation would give the same chunk seed for the world coordinates *(x, y)*, *(y, x)*, *(-x, -y)*, *(x, y)*, etc, resulting in a pretty dodgy pattern to the world.

---

I know games like Minecraft accomplish this, but I cannot find a way to obtain a chunk seed based off of the world coordinates and world seed without there being a weird symmetry in my world generation.

What seed generation method can I use to avoid these symmetries or obvious correlations?

# Answer
> 5 votes
As mentioned in a comment, this problem is solved by hashing.

Here's a naive C# hash function we could use to digest two signed integers into a single positive unsigned int:

```
static uint LocalHash(int x, int y) {
    unchecked {
        uint hash = (uint)x;
        hash ^= (uint)y << 16;
        hash ^= (uint)y >> 16;
        return hash;
    }
}

```

Here we've barrel-shift rotated the bits of y around 16 places, then XOR'd them together with the bits of x. So toggling the low bit of x (travelling between adjacent chunks east/west) toggles the low bit of the hash, and toggling the low bit of y (travelling between adjacent chunks north/south) toggles the 16th bit of the hash. So you have to travel 32 thousand chunks in the x direction before you start to see the same bit patterns you'd seen in nearby chunks in the y direction, and vice versa.

We can make this a seed like so:

```
chunkSeed = LocalHash(chunk.x, chunk.y) ^ worldSeed;

```

This does a good job of ensuring you have a distinct seed for all the chunks in any local area, but it doesn't decorrelate those seeds. So if you use that as a raw input to your random number generator, you might still see correlations between adjacent chunks because of this correlation in their seeds.

You can use more sophisticated hashing functions to blend-up the bits in more complicated ways that mask these correlations, like FNV hash or MurmurHash. For something like procedural generation, you usually don't need the high-end security qualities of a heavier-duty cryptographic hash.

---
Tags: procedural-generation, random
---


# Question
Title: How do I restart an animation that is already playing using SetTrigger?
I have set up a relatively simple example scene with one enemy.

This enemy is controlled with an animation controller. In this animation controller, I have set up a trigger named "Hit".

The enemy plays an idle animation, and when my hero character shoots him, I set the trigger "Hit" via script like this:

```
_animator.SetTrigger("Hit");

```

This causes the animation controller to react to it, and it transitions from "Idle Animation" to "Hit Animation":

The hit animation is 3 seconds long. After it has completed, the animation controller will automatically transition back to the "Idle Animation".

I would like make it so that the hero character can shoot the enemy even though he is already playing the hit animation. Let's imagine you use a machine gun to shoot him repeatedly quickly.

However, when I call

```
_animator.SetTrigger("Hit");

```

while the hit animation is already being played, nothing happens.

As I currently understand it, this makes perfect sense as the Trigger triggers the transition from animation A to animation B, and if we're already at animation B, then there can be no transition.

The transition will only kick in if the animation controller is currently playing the "Idle Animation" as it can then transition to the "Hit animation"

What could I do to "restart" the hit animation?

Thank you.

# Answer
According to DMGregory's suggestion, I have created a transition from "Any State" to "Hit Animation", and now it works. Calling "SetTrigger("Hit")) repeatedly causes a restart of the "Hit Animation".

Also, I have saved a lot of transitions because with "Any State", I can reach all of my "hit" animations (of which I have many, I just removed them for simplicity here) without creating transitions between all animations.

This is what the animation controller now looks like for me:
> 1 votes

---
Tags: unity, mecanim, animation-controller
---


# Question
Title: Texture with Transparent background has black background in Unity
please see the below image. I made a model in Blender that has eye meshes with UV mapped Pupils. But trying to import all this into Unity is causing tons of weird visual errors...

The pupil png has a Transparent background but that background shows up as Black in Unity. Googling says to fix it by choosing 'Transparent' shader but all the ones I try end up cutting out the Eye mesh beneath it.

Any help appreciated.

# Answer
> 1 votes
Problem is SOLVED - It is as simple as making the background color of the Texture png be the color you want the material's 'background color' to be.

In my case: Instead of (a) having a transparent Pupil png over an Eye and hoping the Eye behind would remain white, you are supposed to (b) simply make the Edges of the pupil png white.

Then upload that png into Unity, assign it to the Eye Material Albedo, and set the Png settings in Unity to 'Clamp'. 'Clamp' will stretch the edges of the Texture PNG without deforming the center of your image! :)

---
Tags: unity, textures, image, uv-mapping
---


title: OpenGL shows a black screen

text:
# Question
Title: OpenGL shows a black screen
I am new at OpenGL, I try this example: https://stackoverflow.com/a/31524956/4564882

but I get only a black widget. The code is exactly the same. this is the code associated to the QopenGLWidget:

```
OGLWidget::OGLWidget(QWidget *parent)
: QOpenGLWidget(parent)
 {

 }

 OGLWidget::~OGLWidget()
{

}

 void OGLWidget::initializeGL()
 {
   glClearColor(0,0,0,1);
   glEnable(GL_DEPTH_TEST);
   glEnable(GL_LIGHT0);
   glEnable(GL_LIGHTING);
   glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
   glEnable(GL_COLOR_MATERIAL);
}

 void OGLWidget::paintGL()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

glBegin(GL_TRIANGLES);
    glColor3f(1.0, 0.0, 0.0);
    glVertex3f(-0.5, -0.5, 0);
    glColor3f(0.0, 1.0, 0.0);
    glVertex3f( 0.5, -0.5, 0);
    glColor3f(0.0, 0.0, 1.0);
    glVertex3f( 0.0,  0.5, 0);
glEnd();
 }

 void OGLWidget::resizeGL(int w, int h)
 {
glViewport(0,0,w,h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45, (float)w/h, 0.01, 100.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0,0,5,0,0,0,0,1,0);
  }

```

I tried the example here: https://doc.qt.io/archives/qt-5.3/qtopengl-2dpainting-example.html. It works fine (trying the both base class: QGLWidget and QOpenGLWidget. this is the code associated to the Widget:

```
  GLWidget::GLWidget(Helper *helper, QWidget *parent)
  : QGLWidget(QGLFormat(QGL::SampleBuffers), parent), helper(helper)
 {
 elapsed = 0;
setFixedSize(200, 200);
setAutoFillBackground(false);
}

void GLWidget::animate()
{
 elapsed = (elapsed + qobject_cast<QTimer*>(sender())->interval()) % 1000;
 repaint();
 }

void GLWidget::paintEvent(QPaintEvent *event)
{
QPainter painter;
painter.begin(this);
painter.setRenderHint(QPainter::Antialiasing);
helper->paint(&painter, event, elapsed);
painter.end();
}

```

I use Qt 5.5.1 binairies built on my machine. I let the Build Configuration by default, so it is based on Qt ANGLE not Desktop OpenGL. My Graphic card Driver is updated. What is the problem of such a behaviour?

# Answer
> 0 votes
After a great search, the problem is solved. The problem was because I use Qt5 binaries built with the default configuration. The default in Qt 5.5 is "dynamic" GL -- both ANGLE (ES2)

> ANGLE ((Almost Native Graphics Layer Engine) is an open source project by Google. Its aim is to map OpenGL ES 2.0 API calls to DirectX 9 API.)

and Desktop backends (Desktop OpenGL)are built, the decision on which one to use is taken at runtime.

The problem is that ANGLE only supports OpenGL\>3.x, so the first code that I test is deprecated and not supported by ANGLE. The second is supported, that's why it worked.

So, I rebuild Qt to target Desktop OpenGL only to support my deprecated code, using:

```
configure -debug-and-release -opensource -opengl desktop -platform win32-msvc2015

```

and then

```
nmake

```

I link after that my application to the new binairies, and my code works well!

# Answer
> 0 votes
I had a black screen on desktop. I solved the problem by adding this line of code:

```
QCoreApplication::setAttribute(Qt::AA_UseDesktopOpenGL);

```

For example, put it here:

#include "widget.h"

#include <QApplication>

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_UseDesktopOpenGL);
    QApplication a(argc, argv);
    Widget w;
    w.show();
    return a.exec();
}
```

---
Tags: opengl, c++, qt
---


# Question
Title: what happens when you set transform.position in Unity?
Unity has both `transform.position`and`transform.localPosition`. When I do `transform.position.x += 3f;` does unity automatically update transform.localposition? and vice versa?

Why can I not see this when I go to the definition of `transform.position` in VS?

# Answer
> 1 votes
When you set `transform.position` in Unity, the engine automatically calculates the corresponding local position the object needs relative to its parent to arrive at that location, and sets its local position there.

When you set `transform.localPosition`, the local position is updated directly. Subsequent attempts to read `transform.position` or use any of the `Transform`'s transformation methods will use this new local position - in addition to any parent transforms.

(Don't underestimate your power to find these things out through your own testing - a short script that sets `position` or `localPosition` and prints the values of both before and after would have answered most of your question, much faster than waiting for a stranger to reply here!)

In C# code, this would look something like this:

```
public Vector3 position {
    get {
        if (parent == null)
            return localPosition;

        return parent.TransformPoint(localPosition);
    }

    set {
        if (parent == null)
             localPosition = value;
        else
             localPosition = parent.InverseTransformPoint(value);
        hasChanged = true;
    }
}

```

The reason you don't see this implementation in Visual Studio is likely because this isn't implemented in managed C# code, but in the engine's underlying C++ code, compiled down to a native binary, to which the C# representation just provides a wrapper.

---
Tags: unity
---


title: How do I create a sphere by script?

text:
# Question
Title: How do I create a sphere by script?
I want to add a sphere at runtime via script.

I have the following code which compiles fine. At runtime however, no sphere is added to the scene.

I have attached the debugger to the script, and I have set breakpoints at each line.

After the line

```
Material nMat = new Material(Shader.Find("Lit"));//I'm using the URP

```

the debugger "blanks" out, it doesn't hit the next line.

What am I doing wrong?

Thank you!

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SphereMaker : MonoBehaviour
{
    private GameObject _Sphere;

    void Start()
    {
        _Sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere);
        _Sphere.AddComponent<MeshFilter>();

        MeshRenderer nRenderer = _Sphere.AddComponent<MeshRenderer>();
        Material nMat = new Material(Shader.Find("Lit"));//I'm using the URP

        if (nMat == null)
        {
            Debug.LogError("no mat!!\n");
        }
        nMat.color = Color.red;
        nRenderer.material = nMat;

        _Sphere.transform.localScale = new Vector3(0.4f, 0.4f, 0.4f);
        _Sphere.transform.position = new Vector3(0, 0, 0);

    }
}

```

# Answer
> 0 votes
The shader was not found.

The right name for it would be:

```
Material nMat = new Material(Shader.Find("Universal Render Pipeline/Lit"));//I'm using the URP

```

---
Tags: unity, c#
---


title: Why is this MeshRenderer null?

text:
# Question
Title: Why is this MeshRenderer null?
The following line fails in my class:

```
MeshRenderer nRenderer = _Sphere.AddComponent<MeshRenderer>();

```

This is the entire class. All works except the mentioned line.

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SphereMaker : MonoBehaviour
{
    private GameObject _Sphere;

    void Start()
    {
        _Sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere);
        _Sphere.AddComponent<MeshFilter>();

        MeshRenderer nRenderer = _Sphere.AddComponent<MeshRenderer>();
        Material nMat = new Material(Shader.Find("Universal Render Pipeline/Lit"));//I'm using the URP

        if (nMat == null)
        {
            Debug.LogError("no mat!!\n");
        }
        nMat.color = Color.red;

        nRenderer.material = nMat;

        float fSize = 0.4f;

        _Sphere.transform.localScale = new Vector3(fSize, fSize, fSize);
        _Sphere.transform.position = new Vector3(0, 0, 0);

    }
}

```

Does anybody see what I'm doing wrong?

Thank you!

# Answer
> 1 votes
Obviously,

```
GameObject.CreatePrimitive(PrimitiveType.Sphere);

```

creates a sphere that already has a MeshRenderer, so there is no need to add a new one.

I can get it using this code:

```
MeshRenderer nRenderer = _Sphere.GetComponent<MeshRenderer>();

```

---
Tags: unity, c#
---


# Question
Title: Where can I find the Roblox Material/Terrain textures?
The textures shown in this image: Where can I find them? I am making a Roblox game, it's a terrain based mining game, and I want to add an inventory. Where can I find the textures for the terrain to use as icons? I am not allowed to use screenshots. I am looking for the terrain textures that get rendered, not the icons in the terrain editor. Where in Roblox studio are they located?

# Answer
You can find them inside of the game files. If you're on windows 10, use cortana to search up "Roblox" inside of your apps, right click it, and then press "show file location". Then you can look into the game files and find the textures. Also, if you want to use these as a icon, you will have to first copy and crop these images into squares and then upload it to roblox as a decal. Then you may insert a decal into your gui and insert the ID of the image.
> 1 votes

---
Tags: textures, roblox
---


# Question
Title: Names for specific regions on earth for global RTS
I am developing a global real-time strategy game that uses Google Maps to represent the earth. I am cutting up the globe into 32 squares with each square exactly 45 degrees latitude and longitude. The squares are also aligned to the grid starting from 0,0.

I would like to give each square a nice name that meets the following criteria (in order of priority):

* Every square name must be unique
* Best representation of the land and water contained in the square. Any name is acceptable (country, continent, significant geology, significant body of water) but it must be the most prominent thing in that square
* A combination of names is acceptable if there are 2 or more prominent / recognisable elements in the square
* As short as possible so it can be easy to remember / type
* Exacting precision is not important - this is a game, so the names should be major things in those squares that most lay people on earth would immediately recognise or at least be familiar with
* If possible, the least offensive / non-contested / most globally accepted name of the main region in the square

I have come up with the following, but I would like to know if there is a system already out there that better meets my needs (note that I've accidentally swapped my lat/lngs - sorry!). Alternatively, if anyone has much more knowledge of geology/geography than I do, please suggest a better naming convention and names as some of the names are too long and many contain more country names than I'm happy with (I'd prefer neutral region names):

Here is a map of the world with the 45 degree grid squares shown to help you to visualise the problem:

Edit: Influenced by Phillip's answer, I have revised the approach using continents and oceans to be as neutral as possible:

The only grid squares I'm not 100% sure about are "Middle East" (is this still PC, or is there a better term - Arabia perhaps?), and the Antarctic territories (but since no-one lives there permanently and most countries seem to dispute Antarctic ownership anyway, I think I'm less concerned about this one). Please let me know if this approach is now as appropriate and neutral as possible.

Edit: Further updated based on Theraot's comments:

Notes:

# Answer
> 0 votes
This is the best I can come up with:

I have (retrospectively) applied the following rules / refined my original rules:

1. Prioritise:
    * degrees over anything else
    * continents and largely ignore political boundaries
    * continents (landmass) over oceans (bodies of water)
    * oceans over other bodies of water (primarily seas)
2. Name given must:
    * be unique
    * reflect the largest entity (continent, body of water) in that square
    * reflect only one entity, but breaking it up into northern/southern/eastern/western is ok
    * be as politically correct as possible

Specific callouts:

1. According to my research, "Middle East", despite maybe not being 100% PC is still more politically correct and recgnisable than any alternative proposed. In particular, "Arabia" is a terrible alternative since many people in the Middle East are not Arabs
2. Eurasia as defined in many places is far too large and broad. In my map, it would also encompass Europe, the Middle East and Asia, which would not be accurate/acceptable for most people in those regions (and makes for a less satisfying game experience). I think Eurasia as "Russia" should be acceptable
3. I thought about naming "Western Africa" "North Atlantic Ocean" and renaming that square "The Caribbean" as suggested by Theraot, but it didn't sit well with my prioritising continents and oceans over other bodies of water, particularly over the -45th parallel
4. A lot of the rules get thrown out when it comes to Antarctica as N/S/E/W doesn't reasonably apply. I also didn't want the word "Antarctica" coming up too often as it would seem to make the continent more prominent globally, whereas in reality there are very few resources and almost no people, so acquiring it is not that desirable. I'm happy with Southern Indian Ocean, Indian Ocean, Antarctic Peninsula and Weddell Sea. I'd prefer better names for Queen Maud Land, Wilkes Land, Adelie Land and Marie Byrd Land since:

* they don't follow my continent/ocean rules above
    * they are political names and some are disputed territories
    * most people wouldn't recognise those names

However, given that Antarctica isn't that desirable in a global war game and that very few people would take offence from the names I've given, I think it's an acceptable compromise. Further, that's actually what those regions of Antarctica are called on the map of Antarctica (https://en.wikipedia.org/wiki/Antarctica#/media/File:Antarctica.svg), so maybe I can teach people a thing or two :)

# Answer
> 1 votes
The problem with separating the world into a geometrical grid is that neither geographical nor political borders care about geometrical grids.

Considering that your grid borders do not respect geographical or political borders at all, whatever names you choose, they will either be too long to handle or contain inaccuracies which might potentially cause controversy. And it is pretty easy to accidentally make controversial political statements while carelessly putting names on geographical features. For example, whether you name the water between Saudi Arabia and Iran "Arabian Gulf" or "Persian Gulf" can put you on an embargo list.

So the best solution might be to just refer to them by their grid coordinates. The letter-number system used on many maps might be better for that than using latitude and longitude ("Central Canada" would be A1, "Eastern USA..." would be B2). Not that immersive, but a pretty sure-fire way to dodge any controversy (can't argue with geometry). Your community will likely make up their own unofficial nicknames for some squares, but that's none of your business (as long as it doesn't escalate into harassment).

Alternatively, you could fudge the cell borders in a way which makes them follow real-world continent borders. That way you can name them more accurately and in many cases also avoid to use the names of countries in favor of the names of continents (which usually has less potential for controversies).

We can of course not know how that would affect your desired game experience, because we know nothing about it. But my intuition would tell me that being more flexible with regards to cell boundaries would widen your design space when it comes to redefining borders in order to solve game design issues which you discover while playtesting.

---
Tags: game-design, mmorts
---


# Question
Title: what is the legality behind "openMW" ( an open source implementation of morrowind)
knowing bethesda those people probably sue hard....yet there is an open source implementation of morrowind which is actually quite good. but that question remains, what is the legality behind all of this? is it legal to distribute a free open-source implementation/adaptation of a videogame?

# Answer
The OpenMW project maintains a FAQ page at https://openmw.org/faq/#bethesda\_legal where the legality issue is dealt with.

> ## Does Bethesda Softworks approve of this project? Won’t you guys have legal problems?
>
> Bethesda Softworks is well aware of OpenMW and has given us approval to continue working on it, so long as certain conditions are followed.
>
> We had a long email conversation with Matt Grandstaff which can be read on the wiki. There was a misunderstanding as to what OpenMW is (a new game engine) and isn’t (a Morrowind port) that was cleared up. Bethesda Softworks has asked us to not promote any images or videos of OpenMW running Morrowind on Android or other mobile platforms, and we agreed to comply with this request. Anything else, is fair game, such as displaying videos of OpenMW running the OpenMW-Template on Android on the blog.
>
> We do not condone, nor are responsible, for other websites that show (in images or video) Morrowind running on an Android device.

The Bethesda emails are quite lengthy and numerous so I'll link them rather than quote them: https://wiki.openmw.org/index.php?title=Bethesda\_Emails

> is it legal to distribute a free open-source implementation/adaptation of a videogame?

This is a more general question, and the most appropriate answer to "is is legal to..." questions is "ask a lawyer".

In this case, the developers have approval, in other cases a game engine may be open-sourced but the game assets may remain under a commercial license, other cases may be entirely different. So if you have a specific case in mind, check the licensing terms and if you have doubts, ask a lawyer.
> 3 votes

---
Tags: legal, distribution
---


# Question
Title: Animation via AnimatorController created in script does not play in Unity
I have created an empty `GameObject` and assigned it a script: `Main.cs`.

```
public class Main
{
    [MenuItem("Custom workflow/Initialize")]
    static void Initialize()
    {
        // Place a text mesh on the scene
        var obj = new GameObject("Sample");
        obj.transform.position = new Vector3(0, 0, 0);
        var text = obj.AddComponent<TextMesh>();
        text.text = "Hello world";

        AnimationClip clip1 = CreateAnimationClip();
        AnimatorController sm = CreateSimpleAnimatorController(clip1);

        var animator = obj.AddComponent<Animator>();
        animator.runtimeAnimatorController = sm;
        animator.applyRootMotion = true;
    }

    private static AnimationClip CreateAnimationClip()
    {
        var translateX = AnimationCurve.Linear(0.0f, 0.0f, 2.0f, 25.0f);
        var animationClip = new AnimationClip();
        animationClip.SetCurve("", typeof(Transform), "position.x", translateX);

        AssetDatabase.CreateAsset(animationClip, "Assets/procanim.anim");

        return animationClip;
    }

    private static AnimatorController CreateSimpleAnimatorController(
      Motion motion1 = null, Motion motion2 = null)
    {
        // Creates the controller
        var controller = AnimatorController.CreateAnimatorControllerAtPath(
          "Assets/SimpleStateMachineTransitions.controller");

        // Add parameters
        controller.AddParameter("GoToB", AnimatorControllerParameterType.Bool);
        controller.AddParameter("GoToA", AnimatorControllerParameterType.Bool);

        // Add StateMachines
        var rootStateMachine = controller.layers[0].stateMachine;

        // Add States
        var stateA1 = rootStateMachine.AddState("stateA1");
        stateA1.motion = motion1;
        var stateB1 = rootStateMachine.AddState("stateB1");
        stateB1.motion = motion2;

        // Add Transitions
        var transitionAB = stateA1.AddTransition(stateB1);
        transitionAB.AddCondition(AnimatorConditionMode.If, 0, "GoToB");
        transitionAB.duration = 0;

        var transitionBA = stateB1.AddTransition(stateA1);
        transitionBA.AddCondition(AnimatorConditionMode.If, 0, "GoToA");
        transitionBA.duration = 0;

        return controller;
    }
}

```

### The problem

As I invoke the menu item, I get all assets in place. When I hit play, nothing happens. I can see state `stateA1` is on, but the animation does not run. If I click on the text object in the scene...

...this is what I see in the animation window:

I think the problem might be here:

```
animationClip.SetCurve("", typeof(Transform), "position.x", translateX);

```

Because, when I remove the code generate `Transform.position` property from the animation timeline and manually add one via UI, it works once I hit play again.

# Answer
> 1 votes
The property name I was using is not correct. This will fix the issue:

```
animationClip.SetCurve("", typeof(Transform), "localPosition.x", translateX);

```

The list of properties that can be animated can be found in `EditCurve's doc`.

---
Tags: unity, 3d
---


# Question
Title: Calculate the near clip plane distance in meters from a certain object - Unity
How do you convert the near clip plane and far clip planes to position units, to be able to find out its distance to a game object?

# Answer
The near and far clip planes are already measured in world position units.

```
public struct ClipPlaneDistances {
    public float fromFarPlane;
    public float fromNearPlane;
}

public static ClipPlaneDistances GetDistancesFromClipPlanes(Camera camera, Vector3 point) {
    Vector3 fromCamera = point - camera.transform.position;
    float depth = Vector3.Dot(fromCamera, camera.transform.forward);

    ClipPlaneDistances distances;
    distances.fromNearPlane = depth - camera.nearClipPlane;
    distances.fromFarPlane = camera.farClipPlane - depth;

    return distances;
}

```
> 0 votes

---
Tags: unity, camera, frustum, clipping
---


# Question
Title: Button Press Detection not working while detecting collision
I am trying to make a sign that brings up a panel when you press Enter while the player is over the sign. The code I have written is:

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SignScript : MonoBehaviour
{
    public GameObject Panel;

    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.tag == "Player")
        {
            UnityEngine.Debug.Log("Triggered1");
            if (Input.GetAxis("Submit") == 1)
            {
                UnityEngine.Debug.Log("Triggered2");
                if (Panel == false)
                {
                    Panel.SetActive(true);
                    UnityEngine.Debug.Log("Triggered3");
                }
            }
        }
    }
}

```

I added code that prints "Triggered1", "Triggered2", and "Triggered3" to the Debug Log when you reach certain parts of the code. When the player is over the sign and is pressing Enter, it should print "Triggered2". For some reason, it is not doing this. Does anyone know why?

# Answer
> 0 votes
Here's a neater way, without the bug.

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SignScript : MonoBehaviour
{
    public GameObject panel;

    // Start this script in the disabled state automatically.
    void Reset() {
        enabled = false;
    }

    // Collision events fire even if the script is disabled,
    // so we can use them to wake it up:
    void OnTriggerEnter2D(Collider2D other)
    {
        // Consider using a physics layer that only contains the player,
        // and put this sign on a layer that only collides with the player layer,
        // so you don't even need to check tags: no overlap detection even happens for other stuff.
        if (other.CompareTag("Player"))
            enabled = true; // Start listening.
    }

    void OnTriggerExit2D(Collider2D other)
    {
        if (other.CompareTag("Player"))
            enabled = false; // Stop listening.
    }

    // Runs only when this script is enabled (ie. when a player is in the trigger).
    void Update() {
        // Use a button input for actions like this, not an axis.
        if (Input.GetButtonDown("Submit"))
            panel.SetActive(true);
    }
}

```

# Answer
> 0 votes
I found a solution. It causes one bug that I know of, but it works for right now. The code is:

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SignScript : MonoBehaviour
{
    public GameObject Panel;
    public bool pressingEnter;
    public bool panelNotActive;
    public bool enterPressed;

    void Update()
    {
        if (Input.GetAxis("Submit") == 1)
        {
            pressingEnter = true;
        }

        if(Input.GetAxis("Submit") == 1)
        {
            if(panelNotActive)
            {
                Panel.SetActive(true);
                UnityEngine.Debug.Log("Triggered3");
                enterPressed = true;
                panelNotActive = false;
                pressingEnter = false;
                Destroy(gameObject);
            }
        }

        pressingEnter = false;
    }

    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.tag == "Player")
        {
            UnityEngine.Debug.Log("Triggered1");
            if (Panel.activeSelf == false)
            {
                UnityEngine.Debug.Log("Triggered2");
                panelNotActive = true;
            }
        }
    }
}

```

In Unity, I put the panel I want to bring up on the "Panel" variable. I also made a second script that goes on the panel I am bringing up. The code of that is:

```
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using UnityEngine;

public class PanelScript : MonoBehaviour
{
    public GameObject sign;
    private SignScript signScript;

    // Start is called before the first frame update
    void Start()
    {
        signScript = sign.GetComponent<SignScript>();
    }

    // Update is called once per frame
    void Update()
    {
        if(signScript.enterPressed)
        {
            if (Input.anyKey)
            {
                if(Input.GetAxis("Submit") != 1)
                {
                    gameObject.SetActive(false);
                }

            }
        }
        else if (Input.anyKey)
        {
            gameObject.SetActive(false);
        }
    }
}

```

As I mentioned earlier, this has one bug I know of. The bug is, if you walk past the sign without pressing Enter, the next time you press enter it will bring up the panel. Even though this is okay for now, if anyone knows how to remove the bug or make the code better, feel free to answer. Thanks!

---
Tags: unity, c#, 2d
---


# Question
Title: How do I use a script located not in the Assets folder?
I'm developing several games at once, and they all use the same helper C# class which I have named "Helpers.cs".

This script contains common helper functions.

I'm still making changes to this Helper.cs files quite often, and I have to take care to update this file for all of my projects: If I work at 3 projects as once, I have to make sure I didn't forget to update

```
Project 1\Assets\Scripts\Helpers.cs
Project 2\Assets\Scripts\Helpers.cs
Project 3\Assets\Scripts\Helpers.cs

```

This is error prone.

I would like to know if there is a way to have only 1 "Helper.cs", for example in

```
d:\dev\games\common\Helpers.cs

```

... and all projects would use this. Then I would only have to update the file once if edit it.

I'm using Windows.

Is this possible?

# Answer
> 2 votes
We have a framework shared among our various projects which we have as a git repository. Each project has its own git repository, and references the framework repository as a submodule.

This doesn’t automatically update the different projects, but does make it easier to share code between projects in general.

If you want to avoid using git submodules, you can create a hard link. Note that the source and destination files must be on the same volume. Here’s how to make a hard link in Windows 7, which I think should still apply in Windows 10.

https://superuser.com/questions/255731/make-a-hard-link-without-extra-programs-in-windows-7

If you want to include more than one source file, you could create a symbolic link to an entire directory, but that could cause issues with .meta files shared between projects. Unity has complained about doing that sort of thing in the past. I’m not sure if it still does.

---
Tags: unity, windows
---


# Question
Title: Build Unity3D project from source without Unity Editor
I am trying to create an installer which will download the source of the latest release of a Unity project from a repository hosted on Github and then build it into an executable file. I have tried looking online for a solution, but, they all require the Unity Editor to be installed.

Is it possible to build a Unity project from the source code into a .exe file or a .dmg file without the Unity Editor?

EDIT: From @DMGregory's answer, it seems that using an external tool to build Unity Projects will violate Unity's Terms of Service. Therefore, I am updating the question.

Does Unity provide a lightweight (installer) tool that can allow clients to build and install Unity projects from source rather than requiring the client to install the entire Unity Editor?

# Answer
> 0 votes
Unity's approved method for compiling the source of a Unity project into an executable is to install the Unity Editor - compiling either locally, or using it to communicate with a build server / cloud. That's the only method they offer or authorize.

If anyone were to provide a tool separate from the Unity Editor that could build Unity projects without a licensed Unity Editor installation, it would violate the Unity terms of service:

> **2.6 General Restrictions.**
>
> Except as expressly specified in this Agreement, you may not: (a) copy (except in the course of loading or installing) or modify or **create derivative works of the Unity Software**; (b) distribute, transfer, sublicense, lease, lend, rent or otherwise **provide access to the Unity Software to any third party**; (c) **directly or indirectly make the functionality of the Unity Software available to multiple users or third parties through any means**, including but not limited to by uploading the Unity Software to a network or file-sharing service or through any hosting, application services provider, service bureau, software-as-a-service (SaaS) or any other technology or service; (d) use the Unity Software for competitive analysis or to develop a competing product or service; or (e) do anything that could cause or result in the Unity Software (including the runtime portion thereof) being subject to any open source license (or similar license) that requires as a condition of use, modification or distribution that the Unity Software (including the runtime portion thereof) or other software combined or distributed with the Unity Software be: (i) disclosed or distributed in source code form; (ii) licensed for the purpose of making derivative works; or (iii) redistributable at no charge. You acknowledge and agree that portions of the Unity Software, including but not limited to the source code and the specific design and structure of individual modules or programs, are confidential and constitute or contain trade secrets of Unity and its licensors. Accordingly, you agree not to disassemble, decompile, modify or reverse engineer the Unity Software, in whole or in part, or permit or authorize a third party to do so, except to the extent such activities are expressly permitted by this Agreement or by law notwithstanding this prohibition. Notwithstanding the restriction prohibiting decompiling in the immediately preceding sentence, you may decompile the Unity Common Language Infrastructure (CLI) assemblies solely to inspect their functionality for purposes of understanding or improving performance of your Project Content or any editor extension to the Unity Software.

# Answer
> 1 votes
You could provide a pre-built .exe, whose job is to just load a .dll containing the main game code. Then the installer (presumably not written in Unity) could theoretically build the .dll from the source files, referencing the main Unity dll included in the project as necessary.

This could theoretically work for Windows, using the C# compiler included in the .NET Framework, and if it does, I assume it could also work for Mac, but I’m not sure.

---
Tags: unity, build-process, installer
---


title: Creating a Pawn that simulates physics

text:
# Question
Title: Creating a Pawn that simulates physics
I'm trying to make a Pawn that I can raycast against. Starting from the DefaultPawn object, I can't find a way to have a StaticMesh cube that simulates physics. My raycasting code works with Actors, but I'd like to apply the same feature to moving objects now.

Any advice on how to achieve this?

# Answer
Using a DefaultPawn object allows to have a Pawn with physics. In order to Raytrace against Pawns, it is necessary to specify `ECollisionChannel::ECC_Pawn` when calling `LineTraceSingleByObjectType`.
> 0 votes

---
Tags: physics, unreal-4
---


# Question
Title: How do I end a behavior tree's action early without evaluating the entire active branch?
I'm reading about behavior trees, and one of the common recommendations I've seen is to maintain a reference to your running action so that you don't have to traverse the entire tree during every game loop. Without traversing the entire tree every time, how do I check if an action should end early?

For example, suppose I have the following tree and the AI encounters an enemy that's closer than 10m, so he starts to aim his weapon. But then while he's aiming, his HP drops below 50%. I would want the agent to stop the aiming/firing sequence and move to the "use medkit" action.

The only way that I can think of to accomplish that sort of behavior is to evaluate every node in the active branch -- starting from the root node -- during every game loop. But based on what I've read, evaluating the entire active branch every game loop is discouraged.

Is there a way to be able to abort an action if a higher-level node is no longer valid, while not spending a lot of processing power evaluating the entire branch every game loop?

# Answer
> 3 votes
That is not how you do do decisions in a behavior tree.

If I understand correctly, your tree has this logic:

```
while(true)
{
    if (HP > 50%)
    {
        if (Visible enemy closer than 10m)
        {
            Aim Weapon
            Fire Weapon
        }
        else
        {
            Move
        }
    }
    else
    {
        Use Medkit
    }
}

```

This is how you should express it:

```
selector
{
    sequence
    {
        HP > 50%
        selector
        {
            sequence
            {
                Visible enemy closer than 10m
                Aim Weapon
                Fire Weapon
            }
            Move
        }
    }
    Use Medkit
}

```

Let go over it, starting from the most inner part:

```
            sequence
            {
                Visible enemy closer than 10m
                Aim Weapon
                Fire Weapon
            }

```

This is a `sequence`, it will succeed if all its tasks succeed. Fail as soon as one fails. That means that if `Visible enemy closer than 10m` fails, you don't run `Aim Weapon` and `Fire Weapon`. Similarly, if `Aim Weapon` fails, you don't run `Fire Weapon`.

Next is this:

```
        selector
        {
            sequence
            {
                Visible enemy closer than 10m
                Aim Weapon
                Fire Weapon
            }
            Move
        }

```

This is a `selector`, it will fail if all its tasks fail. Succeed as soon as one succeeds. That means that if the sequences we reviewed before succeeds you don't run `Move`. That means that `Move` only runs when `Visible enemy closer than 10m` (or any other task of the sequence) fails.

Next up:

```
    sequence
    {
        HP > 50%
        selector
        {
            sequence
            {
                Visible enemy closer than 10m
                Aim Weapon
                Fire Weapon
            }
            Move
        }
    }

```

Hopefully, you can see how this works… If `HP > 50%` fails, you don't go into the selector.

Finally:

```
selector
{
    sequence
    {
        HP > 50%
        selector
        {
            sequence
            {
                Visible enemy closer than 10m
                Aim Weapon
                Fire Weapon
            }
            Move
        }
    }
    Use Medkit
}

```

As you can see, if the prior sequence succeeds (which implies that `HP > 50%` succeeds), then you don't run `Use Medkit`. In fact, `Use Medkit` would only run in scenarios where `HP > 50%` failed.

---

> For example, suppose I have the following tree and the AI encounters an enemy that's closer than 10m, so he starts to aim his weapon. But then while he's aiming, his HP drops below 50%. I would want the agent to stop the aiming/firing sequence and move to the "use medkit" action.

You would have to add a task that fails the sequence, for example:

```
selector
{
    sequence
    {
        HP > 50%
        selector
        {
            sequence
            {
                Visible enemy closer than 10m
                HP > 50%
                Aim Weapon
                Fire Weapon
            }
            Move
        }
    }
    Use Medkit
}

```

Now, the agent checks its health before aiming, and if did drop below 50%, it will move… Wait, that is not what you want.

We can of course do this:

```
selector
{
    sequence
    {
        HP > 50%
        selector
        {
            sequence
            {
                Visible enemy closer than 10m
                HP > 50%
                Aim Weapon
                Fire Weapon
            }
            sequence
            {
                HP > 50%
                Move
            }
        }
    }
    Use Medkit
}

```

And we don't need to check health above, do we?

```
selector
{
    selector
    {
        sequence
        {
            Visible enemy closer than 10m
            HP > 50%
            Aim Weapon
            Fire Weapon
        }
        sequence
        {
            HP > 50%
            Move
        }
    }
    sequence
    {
        HP < 50%
        Use Medkit
    }
}

```

No need for nested selectors, either:

```
selector
{
    sequence
    {
        Visible enemy closer than 10m
        HP > 50%
        Aim Weapon
        Fire Weapon
    }
    sequence
    {
        HP > 50%
        Move
    }
    sequence
    {
        HP < 50%
        Use Medkit
    }
}

```

This is an useful pattern: make a selector of sequences, where each sequence lists its preconditions.

Right, but, we don't want to repeat ourselves…

Take advantage of the order in the selector:

```
selector
{
    sequence
    {
        HP < 50%
        Use Medkit
    }
    sequence
    {
        Visible enemy closer than 10m
        Aim Weapon
        Fire Weapon
    }
    Move
}

```

As you can see, this agent will only `Use Medkit` when `HP < 50%` succeeds. And if that succeeds, it will not aim or move. In other words, it only aims or move given that `HP < 50%` failed.

---

Right, but what if the health fell between aiming and firing?

There is no concept of aborting a tasks in behavior trees. Instead a task could translate to any code you want to run, and that code may fail. Thus, you could package the preconditions in the task.

---

It is a design principle of behavior trees to make tasks fast. If aiming takes time don't have the tree handle it.

We already have an idea of state: HP. Let us go further. We will have a target enemy.

```
selector
{
    sequence
    {
        HP < 50%
        Use Medkit
    }
    sequence
    {
        Has selected enemy
        Aim at enemy
    }
    sequence
    {
        Has aimed enemy
        Fire weapon
    }
    sequence
    {
        Find visible enemy closer than 10m
        Set selected enemy
    }
    Move
}

```

Perhaps aiming does not have to exist in the tree. Instead, if there is an enemy selected, an animation subsystem would handle aiming at it (and might even do it while moving).

However, imagine aiming happens asynchronously… Or perhaps imagine it happens beyond the control of the tree, just like losing HP happens beyond the control of the tree. However, once the agent has aimed an enemy, the tree should decide to fire the weapon.

---
Tags: ai, behavior-tree
---


title: Game networking , server send rate

text:
# Question
Title: Game networking , server send rate
I've been writing some server code recently and I ran into a bottleneck. If a server is capable of sending data at 60hz, with 1 client it would send data to that client at 60z, with 2 clients this would drop to 30z, then with 3 clients to 20hz,etc... This is because the server can only send data to one client at a time, Is my logic correct here? For example, if I had 50 clients and I wanted each client to receive 60 updates per second the server would have to tick at (60hz x 50 clients) 3000hz!?

Is there a more efficient way this is done?

# Answer
> 2 votes
Let us talk time budgets.

First of all, the rate at which the server sends updates, and the rate at which the client renders don't have to match. Many games will send updates less frequently than the client renders.

With that said, the server will have some time to get the input, simulate and send the updates. Let us say, a 1/60 of a second.

Getting input should not take long. The system will queue network input, and at the start of the cycle the server just takes whatever is in there.

Simulation will take some time. It might depend on the number of players. However, depending on the kind of game, there could be a remarkable amount of work that the server will do in simulation regardless of the number of players (physics and AI).

And finally the server sends the updates, which takes some time that grows linearly with the number of clients. However, hopefully these take little CPU time, as they are only sending data that was updated in the simulation, and the actual sending can be done asynchronously (and taking advantage of DMA).

So, you have time budget. Say 1/60 of a second. And you got to expend it in doing these things. Perhaps you don't use it all. If there is some wiggle room, you could take more players without a drop in performance. Otherwise, getting more players could mean allocating less time for simulation. And of course, you can get more powerful hardware.

---

Where is your bottleneck, exactly? It could be the CPU time, which is what I'm talking about above… Or it could be transference rate ("bandwidth"). Your network connection will cap your transference rate. If this is the bottleneck, then another option is to send less information to each player.

Some games will send less information in highly populated areas. For example, you get your full move set in instances, but in hub areas your movement is restricted (not using weapons, not running, and so on). This allows for simpler updates in hub areas.

Also, as you know, there is no point in sending updates about everything in the game, only about nearby objects and high priority updates. *Since the client may stop receiving updates about an object for a while, eventually it is cheaper to send the whole state of the object than sending all the updates since the client last recieved.*

---

I'll remind you that it is better to use UDP and build your own reliability models than using TCP. You don't want the server waiting on acknowledge packages, and you don't want acknowledge packages eating transference rate. Much less if what you are sending all the time are updates, you don't have to worry about a missed update if the next update overwrites it.

---

I also want to mention threading. It is possible to have a thread dedicated to the network connection for each client. *In fact, this is the natural way with some network APIs.* That means you could send data to multiple clients in parallel (limited by the number of cores on your machine, of course).

---

Finally, I have read that it is possible to use multicast in some scenarios (I have no experience implementing this). The idea is that the clients and the server would join a multicast group (done by telling the router), which will have a multicast address, and then the server will send to that address. The routers that support multicast will replicate the messages on the network.

---
Tags: networking, client-server
---


title: Enemy fire every few seconds

text:
# Question
Title: Enemy fire every few seconds
Hi I'm trying to get my enemy to fire once every few seconds, I tried using a Coroutine but due to me essentially calling the Coroutine through the update method, the Coroutine is repeating every frame update and spamming the shoot key. What is a solution for this?

```
void Update () {
        Shoot ();
}

public void Shoot(){

        StartCoroutine ("ShootContinuous");

}

public IEnumerator ShootContinuous() {
    yield return new WaitForSeconds (1);
    anim.SetTrigger("Shoot");
    Instantiate (Bullet, firePoint.position, firePoint.rotation);
    isShooting = true;
    yield return new WaitForSeconds (1);
    anim.SetTrigger("NoShoot");
    isShooting = false;

}

```

# Answer
> 2 votes
I've found that making a looping script works well for an attack timer, and avoids the problems that come with using a coroutine to time something. Bonus here is that you can use this anywhere in your scripts for an easy timer.

```
private bool canAttack; //This gets changed when the enemy can try and shoot at you (ie. within range)

private float newFireTime; //This holds the time for the next shot
private float stopFireTime; //Holds the time for when you want to change your anim
private float firingDelay; //The delay in seconds you set (ie a value of "2" means 1 shot every 2 seconds)

private bool attackLoopStarted;

void Update()
{
    if(canAttack)
    {
        AttackTimer();
    }
}

private void AttackTimer()
{
    if (!attackLoopStarted) //If the attack loop has not been initiated
    {
        attackLoopStarted = true; //Signal the loop has been started
        newFireTime = Time.time + (1 / fireRate); //Takes your fire delay in seconds and converts it to shots Per second and record this
        stopFireTime = Time.time + (1 / stopFireTime); // Same as above, except for your animation
        Shoot(); //Call your method to initiate an attack
    }

    if (attackLoopStarted) //Once the attack loop has started check the time against the future time
    {
        //If the gametime is greater than or equal to the newFireTime, then set the bool to false to restart the loop
        if (Time.time >= newFireTime)
        {
            attackLoopStarted = false;
        }
        //Will only check when isShooting is true, will change the aniamtion after your specified time
        else if (Time.time >= stopFireTime && isShooting == true)
        {
            StopShoot(); //Call method to change your anim and set the isShooting bool to false
        }
    }
}

private void Shoot()
{
    anim.SetTrigger("Shoot");
    Instantiate(Bullet, firePoint.position, firePoint.rotation);
    isShooting = true;
}

private void StopShoot()
{
    anim.SetTrigger("NoShoot");
    isShooting = false;
}

```

Edit: This exact code will present a bug if your fire delay, and the delay for your animation are exactly the same (say you want to shoot every 2 seconds and you want the animation to change every 2 seconds at the exact time of the shot, which would probably work against what I believe you are trying to accomplish). You can fix that by replacing `stopFireTime = Time.time + (1 / stopFireTime);` with `stopFireTime = Time.time + (1 / fireRate / 2);`that will casue the animation to change back from firing to not firing 1/2 way between shots.

# Answer
> 1 votes
If you don't want them stacking up, just use a bool for a flag.

```
bool inShootingLoop = false; //keep track of when the coroutine is running

public void Shoot(){
    if(!inShootingLoop)
        StartCoroutine ("ShootContinuous");
}

public IEnumerator ShootContinuous() {
    inShootingLoop = true; //we're running, set this to make sure we don't start again
    yield return new WaitForSeconds (1);
    anim.SetTrigger("Shoot");
    Instantiate (Bullet, firePoint.position, firePoint.rotation);
    isShooting = true;
    yield return new WaitForSeconds (1);
    anim.SetTrigger("NoShoot");
    isShooting = false;
    inShootingLoop = false; //we're done, set this to allow another iteration
}

```

Or you can just run your coroutine forever:

```
public IEnumerator ShootContinuous() {
    while(true) {
        yield return new WaitForSeconds (1);
        anim.SetTrigger("Shoot");
        Instantiate (Bullet, firePoint.position, firePoint.rotation);
        isShooting = true;
        yield return new WaitForSeconds (1);
        anim.SetTrigger("NoShoot");
        isShooting = false;
    }
}

```

# Answer
> 1 votes
The problem is that the ShootContinuous() Coroutine is in Shoot() and Shoot() is in Update() which means the Coroutine ShootContinuously is in Update(). So a new ShootCountinuously() Coroutine is started for every frame. The below method starts only one Coroutine which will repeat Continuously.

```
void Start ()
{
   Shoot ();
}

public void Shoot()
{
    StartCoroutine (ShootContinuous());
}

public IEnumerator ShootContinuous()
{
    while(true)
    {
        yield return new WaitForSeconds (1);
        anim.SetTrigger("Shoot");
        Instantiate (Bullet, firePoint.position, firePoint.rotation);
        isShooting = true;
        yield return new WaitForSeconds (1);
        anim.SetTrigger("NoShoot");
        isShooting = false;
    }
}

```

Note: ***Never start a coroutine in Update()***

---
Tags: c#, unity
---


# Question
Title: When importing a character to Unity, textures and meshes don't appear
I'm relatively new to Unity, and I'm left with doing this as my last step towards my task - importing my animated character to a game engine and program the movements.

The problems that I have noticed are the missing textures and meshes, you can see in the first picture how it should look like in Blender, and what results I get in Unity:

The apple here doesn't have any holes, I think only one material got imported, and it doesn't look right. Textures are missing, the leaf near the stem is completely filled with gray texture. At least the animations work perfectly...

Download link to my .blend file - https://pasteall.org/blend/6c14ec0d9446404b81251585f83f3551

# Answer
If you colored it with texture painting you need to import the texture to unity and if it still uncolorized you need to drag the texture to objects material.
> 1 votes

---
Tags: unity, textures, blender, models, 3d-meshes
---


# Question
Title: MissingComponentException when using Animator
I followed some tutorials to add WASD movement to a character; I managed to set up the animator thing and it works in the bottom right corner viewport.

Next I tried adding the following C# script with basic movements:

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AppleInput : MonoBehaviour
{
    private Animator animator;
    // Start is called before the first frame update
    void Start()
    {
        animator = GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {
        animator.SetFloat("Horizontal", Input.GetAxis("Horizontal"));
        animator.SetFloat("Vertical", Input.GetAxis("Vertical"));
    }
}

```

Configured like so:

But then I get the error message:

> MissingComponentException: There is no 'Animator' attached to the "action10Prob\_normalsDONEyet" game object, but a script is trying to access it.
>
> You probably need to add a Animator to the game object "action10Prob\_normalsDONEyet". Or your script needs to check if the component is attached before using it.

How do I solve this error?

# Answer
This line:

```
animator = GetComponent<Animator>();

```

...says "find an `Animator` type component attached to the *same* `GameObject` that I (`AppleInput`) am attached to.

But as we can see in your screenshot, you don't have an `Animator` component on the object "action10Prob\_normalsDONEyet". So this line is returning a `null` (really, a special dummy component that the Unity Editor uses to give you better error messages when testing).

When your `Update` code tries to use the animator like so:

```
animator.SetFloat("Horizontal", Input.GetAxis("Horizontal"));

```

Then you get the error message: you tried to call `SetFloat` on the *absence of* an `Animator`.

The fix for this will depend on your setup. If you already have an `Animator`, but it's somewhere in a child object under this one, you can either:

* Change `GetComponent<Animator>` to `GetComponentInChildren<Animator>` to search child objects too.
* Or, get rid of this top parent object, and put your `AppleInput` script on whichever child has an `Animator` attached directly instead.
* Or, make your `Animator animator` variable `public` so that you can use the Unity Inspector to assign a reference to whichever `Animator` you want to use.

If you *don't* have an `Animator` component anywhere in the object hierarchy, then it's time to add one to the object with the `AppleInput` script, so it can find it where it's trying to look for it.

Note that this is one of the most common beginner errors in Unity, so just searching "MissingComponentException unity" will turn up tons of existing answers and documentation about it. So please always make that your first step when troubleshooting an error message.
> 0 votes

---
Tags: unity, c#, animation
---