#archived-code-advanced

1 messages · Page 66 of 1

misty glade
#

Storytime - in our first month of operations we noticed really aggressive port scanning - TCP connections on every port in sequence from a variety of IP addresses around the world (obvious VPN/botnet). About 24hrs after the connection was made on the actual game port, we'd see a variety of malformed packets come in with all kinds of funny data. Invalid headers, mostly, but the valid headers contained just a slew of different kinds of requests.. HELO and GET index.html and stuff like that. I'm pretty sure we still get malformed header connections just around the clock.

I was confused, thought maybe it was azure health checks or perimeter stuff, they (MS) confirmed it wasn't, so I change the game port (at great pain) and the same cycle happened again

plush hare
#

yeah port scans are gonna happen no matter who your provider is

misty glade
#

yeah we still get them

plush hare
#

But yeah this is going to get pretty complex. Someone else will probably have better suggestions

misty glade
#

I think doing the microservices and location servers will be best. I know that's how EVE online does it, and I think diablo3 too.. Like, you'd have a chat server handle all chat, a zone server that would handle players in some fixed zone in real time, maybe an achievment server, etc.. It just gets wonky when one of those services go down and you're still able to play but chat isn't working

plush hare
#

You'd probably just be better straight up disconnecting clients when your blades go down. Or perhaps give them a warning. Or wait until it's like 2am to shut it down

#

I know some providers charge based on resources rather than time

misty glade
#

Yeah but even an "empty" blade is still gonna be consuming resources, not a lot, but some.. It might not be a huge deal to have a bunch of blades running empty, so long as they're not being too aggressive on database hits.

The more I think around this, though, the more I think that there's just not going to be an easy/magic solution - the restful api approach is interesting but probably creates more problems than it solves, and certainly each request is going to come with a lot of baggage. I think I'm just gonna need to code my way out of this and build the blade/lobby/microservice approach

#

Oh, the other "pro" for web/restful is that people with shit connections can have a slightly better experience - versus what happens now which is.. kinda crappy. We have to set a keepalive time (both for clients and server) so we know when one or the other disconnects, and it's a guessing game.. 15 second pings that don't come back within 60 is our current amount, preventing people from getting disconnected in tunnels (they just "catch up" when they come back to service) but not playing as a zombie and losing too much progress they never actually had because the connection went dead

plush hare
#

If that azure tunnel shit gives you too many problems, you should just switch providers

#

I don't know if azure is designed for realtime stuff like this. I think they're more geared towards the web market

#

ovh has like a 7 tbps backbone and automatically reroutes ddos to scrubbing centers. free of charge. No tunneling bs required

green pagoda
#

ok thanks

gloomy mica
#

is there any quick ways to determine what these byte[] is?

#

screenshot is from memory profiler

gloomy mica
worthy vapor
#

hello, i have multiple meshes of countries, and i wanted to generate a random point on the country, i have tried a lot of things with Chat GPT but every time, the repartition is uneven, clustered, or always on the border, maybe it is due to the special shape of my mesh but i'm starting to want to give up ...
(attched, two screens of the mesh used for Spain)

tiny pewter
#

there is a general algorithm for pick random point of any polygon

#

you need to trangulate your polygon first then select one triangle based on their area/ total area and pick one point in the triangle you have selected

#

maintain a ordered list of triangle based on their area can help you pick the triangle in O(log n) time

tall ferry
#

Is this not just weighted randomness based on area of triangles?

tiny pewter
#

yes exactly

worthy vapor
#

i also want to ingore triangles that are not facing upwards

tiny pewter
#

you can construct two vectors by three vertice of triangle and cross them
i dont know if there is built in api can help you do this

worthy vapor
tall ferry
vestal condor
#

Quick C# question - let's say I want to have a delegate that is "public" in terms of adding to it but can only be privately invoked
Is there some syntatic sugar for this or do I just need to add boilerplate code?

#
public delegate void EnemyEvent(Enemy enemy);
private EnemyEvent OnEnemySpawn;

Is there a good way to add a method to OnEnemySpawn without boilerplate code and achieving the same outcome?

dusty wigeon
vestal condor
#

Hmm, maybe I was unclear

class Spawner 
{
  public delegate void EnemyEvent(Enemy enemy);
  private EnemyEvent OnEnemySpawn;
}

class Wave
{
  ...
}

I would like the Wave class to be able to add a method to OnEnemySpawn in Spawner but not be able to call OnEnemySpawn(...)
sort of like a write only rather than a read only

dusty wigeon
#

Alternatively, you can implement manually the Observer pattern and control visibility base on your preference.

vestal condor
#

Aha, thanks I was looking for event.

plucky laurel
#

will save you some typing in 90% of cases

#

public event Action<Enemy> onEnemySpawn;

wise tartan
#

So question, is it good practice to use async in Unity? From what I've read the problem is that Unity is designed to run on a single thread, and async operations can get a bit messy if you're dealing with Unity features specifically.

From what I understand Coroutines are supposed to replace that, but I feel like they're a little finnicky?

plucky laurel
#

async isnt threaded

#

yes you can use async, there are several implementations of it

austere jewel
plucky laurel
#

Coroutines/ their better alternative MEC on asset store/ .net async / UniTask on github

austere jewel
#

Practically, yes

wise tartan
#

What does it add to working with async operations? I haven't studied async too much, so I'm still a little lost

#

Awaitable, that is

#

Right now you'd have to return Task to assess the state of an async operation, right? Is it a replacement for that, with more Unity integration?

plucky laurel
#

it returns an object that unity understands, ie wait for a frame, wait til some unity state is reached etc

#

so the state machine higher can suspend/resume the method at appropriate time, same as coroutines yield objects, as i understand it

#

with UniTask it injects itself into the playerloop, at specific points before/after update etc, then catches UniTask struct and makes decisions on when to continue the method

#

also its a struct, Awaitable is an object, which is weird

austere jewel
# wise tartan What does it add to working with async operations? I haven't studied async too m...
Awaitable Coroutines are async/await compatible types specially tailored for running in Unity. (they can be awaited, and they can be used as return type of an async method)
 Compared to System.Threading.Tasks it is much less smart and takes shortcuts to improve performance based on Unity specific assumption.
 Main differences compared to .net tasks:
  • Can be awaited only once: a given Awaitable object can't be awaited by multiple async functions. This is considered undefined behaviour (considering it undefined behaviour allows for optimizations non-achievable otherwise)
  • Never capture an ExecutionContext: for security purposes, .net Tasks capture execution contexts on awaiting to be able to handle things like propagating impersonnation contexts accross async calls. We don't want to support that and can eliminate associated costs
#
  • Never capture Synchronization context:
    Coroutines continuations are run synchronously from the code raising the completion. In most cases, it will be from the Unity main frame (eg. for Delayed Call Coroutines and existing AsyncOperations)
    Methods returning awaitable coroutines with completion being raised in a background thread will need to mention it explicitly in their documentation
  • Awaiter.GetResults won't block until completion. Calling GetResults() before the operation is completed is an undefined behaviour
  • Are pooled object:
    Those are reference types, so that they can be referenced accross different stacks, efficiently copied etc, but to avoid too many allocations, they are pooled. ObjectPool has been enhanced a bit to account to avoid Stack<T> bounds checks with common get/release patterns produced by async state machines
  • Can be implemented in either managed or native code:
    There is Scripting::Awaitables::Awaitable base class providing interop with this managed coroutine type, that can be extended so that Native asynchronous code can be exposed as an await-compatible type in user code.
    See AsyncOperationCoroutine implementation as an example
#

(that is a comment above Awaitable in the Unity source)

wise tartan
#

This is some dense stuff... thank you

#

https://docs.unity3d.com/2023.2/Documentation/Manual/AwaitSupport.html

{
    var apiResult = await SomeMethodReturningATask(); // or any await-compatible type
    JsonConvert.DeserializeObject<List<Achievement>>(apiResult);
}

async Awaitable ShowAchievementsView()
{
    ShowLoadingOverlay();
    var achievements = await GetAchievementsAsync();
    HideLoadingOverlay();
    ShowAchivementsList(achievements);
}```

i struggle to understand the `GetAchievementsAsync()` method from the documentation, it doesnt seem to have a `return`? am i just misunderstanding something about async?
plucky laurel
#

there is await in it

austere jewel
wise tartan
#

How is the apiResult returned to ShowAchievementsView through the await?

austere jewel
#

Because it would return Awaitable<string> or similar

#

when you await the Awaitable it practically evaluates and unpacks it, so you get the value it returned

wise tartan
plucky laurel
wise tartan
#

ok good cause i thought i was going crazy

wise tartan
#

So if i understand correctly
await Awaitable.BackgroundThreadAsync();
or
await Awaitable.MainThreadAsync();
just basically toggle any following code to run on the respective thread?

bleak citrus
#

this performs poorly for pathological cases, like a country shaped like a very very thin donut

novel plinth
wise tartan
#

Interesting, thanks

worthy vapor
bleak citrus
#

I have code that does that somewhere

#

it was used to sample a random point on a navmesh

#

note that this is not a uniform distribution, since the tris could have different sizes

#
Vector3 GetRandomLocation()
    {
        NavMeshTriangulation navMeshData = NavMesh.CalculateTriangulation();

        // Pick the first indice of a random triangle in the nav mesh
        int t = Random.Range(0, navMeshData.indices.Length-3);
        
        // Select a random point on it
        Vector3 point = Vector3.Lerp(navMeshData.vertices[navMeshData.indices[t]], navMeshData.vertices[navMeshData.indices[t+1]], Random.value);
        Vector3.Lerp(point, navMeshData.vertices[navMeshData.indices[t+2]], Random.value);

        return point;
    }
#

you know, i just realized that this might pick one vertex from one triangle and two vertices from another triangle

#

not sure

#

i am also not confident that this even produces a uniform distribution across the single triangle...

last locust
#

new rule no more refunds

#

Everythings free

upbeat path
last locust
#

Anything advanced

unborn relic
#

hello, i am having trouble understanding something. if I fire some Jobs that take let's say 2 seconds to finish each, if I wait for them to complete with jobhandle.Complete(), the main thread is still going to be stuck for 2 seconds right? how do I avoid this? do I need to have a croroutine that checks if the jobhandle is complete, or yield return new WaitForEndOfFrame() if not? is there a better way?

real blaze
#

if it's possible however, you can move your whole method to another thread, and just stop the thread untill all jobs are done using that Complete(). this will have less overhead, if you need to do a lot of work in the jobs. which it seems you are

unborn relic
real blaze
sage radish
#

You can, it's one of the methods they made thread safe.

dawn zephyr
#

hey guys would a zenject scenecontext with an installer with dontdestroyonload work in order to inject things in another scene?

#

That's my installer, maybe im doing something wrong, just picked up zenject

public class Installer : MonoInstaller
{
    [SerializeField] private DatabaseManager _databaseManager;
    public override void InstallBindings()
    {
        Container.Bind<IDatabase>().To<DatabaseManager>().FromInstance(_databaseManager);
    }
    private void Awake()
    {
        DontDestroyOnLoad(gameObject);
    }
}

And the class

public abstract class DatabaseDependant : MonoBehaviour
{
    [Inject] protected IDatabase _database;
    protected abstract void LoadData();
    protected abstract void SaveData();
    protected virtual void Start() => LoadData();
    private void OnApplicationPause(bool pause)
    {
        if (!pause)
        {
            return;
        }
        SaveData();
    }
    #region DEBUG
    private void OnApplicationQuit()
    {
        SaveData();
    }
    #endregion
}

my database doesnt get injected for some reason

sage radish
vestal condor
#

I'm having this issue where reloading script assemblies takes really long 30-60s after changing any bit of code at all
any idea what could be causing this?

dull kestrel
novel plinth
#

nah, dont disable it unless you know what you're doing

novel plinth
vestal condor
#

alright I’ll take a look

#

It didnt take this long back then though, not that I recall at least

dull kestrel
vestal condor
#

hm what’s fishnet?

#

i do have this dependency hunter thing but i don’t think it runs unless i tell it to

#

maybe i should investigate that

dull kestrel
dusty wigeon
#

Pretty sure you can profile also. On our project (Not divided by assembly (-_-)), we have 10s. Sometimes it goes in the 30s and a good restart (Computer) works.

bleak citrus
#

this has absolutely nothing to do with unity

austere jewel
#

This is a Unity server, so no, if it's not Unity-related it's off-topic

dawn zephyr
dawn zephyr
#

Man it's killing me it's just one line of code I can't wrap my head around why it isnt working

flat mountain
#

Is there a way to get the currently active material whilst rendering Editor IMGUI?

Trying to figure out which material is being used so that I can use it in my line rendering and retain the clip (which Internal-Color, as I learnt the hard way, doesn't do)

timber flame
#

I have big problems to design an architecture for my data in a city building game (simulation survival game) like oxygen not included. In my game, there is different buildings, plants, etc.
I can inherit them from a base class BuildingDefinition and then specific child type ResourceBuildingDefinition, PlantDefinition, etc.
The problem is
1- It is possible to add another hierarchy.
2- Sometimes, it is hard to add some fields to base class or put them in individual child classes. For example Hitpoint. Maybe, some buildings have hitpoint or not (cannot damage). I know I can add a boolean field canHit to base class BuildingDefinition but...
the design of this game is really incomplete and I do not know which architecture is the best in this situation, component based or inheritance. I know component based approach is more flexible and I generally prefer it even for data (scriptable object definitions)

Building Data
Damageable component
Construction component --> build time, required resources, etc.
Specific components for each building
BaseComponent --> name, icon, etc.

dawn zephyr
#

maybe a damageable interface?

timber flame
#

They are data attached to that scriptableobject not mono.

#
public class BuildingDef:ScriptableObject{
   public IComponnet[] Components;
}
dawn zephyr
#

try the serializereference attribute

timber flame
#

My question is not how I can implement it

#

It is about architecture if somebody has any experience to structure their data using component list or inheritance with different children

plucky laurel
#

@timber flame you have odin?

#

with odin you can directly serialize your components in the scriptable, with polymorphism and all

#

at runtime you clone it from the def

#

i dont fully understand what you already have, but it looks like you decided to use composition for defs

#

so list of defs that are responsible for various aspects of the thing

#

i dont think there is a game that would not rigidify at some point, where all the excess modularity would only hinder your design time

#

composition sounds great if you have a good way to edit all of that, like [InlineEditor], and a custom window with all your data split into tabs, etc

#

if its done well you wont have to spend time in the project panel

timber flame
#

So, you like me prefer to organize your data as component list?

plucky laurel
#

when im weighing the costs i take into account things like - ease for designers, amount of additional objects you have to maintain (drawers, runtime representations),
amount of cases that would result from modularity, i.e. if its something like a script for a spell, is it reasonable to construct it from basic atomic blocks, similar to visual scripting?
maybe it is, but this will result in an explosion of maintenance cost

#

so i tend to lean towards plain pods as much as possible, you can migrate data later if needed, but from the get go creating yourself a bunch of maintenance which benefit cant be easily predicted in the long run, is akin to premature optimization, overengineering

#

in 90% of cases it never goes further than a pod

timber flame
#

No, I do not want to break them and create them from atomic blocks

#

Probably, the number of components do not exceed 10.

plucky laurel
#

look at it like this, right now you have say a building that is modular, then you adhere to that paradigm and eventually you will have everything in the project modular, thousands classes to maintain, architecture to handle it all, draw/edit it all, you have to remember which components you have for each thing, what goes where, what to use when etc

#

just envision the end state of the project if it was this way, and if you are ok with it, go for it

timber flame
#

but at this moment, I do not know for example every building has damage. Every building has ... and so one to use inheritance with base data

plucky laurel
#

yes but every building damage can be described as bool isDamageable

timber flame
#

Yes, I can define all data for all of them with default values if they do not have them

timber flame
#
public class Buidling: ScriptableObject
{
   public bool IsDamageable;
   public int HitPoint;
   public Resource[] Inputs;
   public Resource[] Outputs;
}
public class Plant:Building{
   // specific properties for plants (grow rate, conditions, etc.)
}
public class Military:Building{
  // attack point, rate, etc.
}

Inputs and outputs can be resource or something different completely.

plucky laurel
#

i like this approach as a base one, you have the power of the type system, you can infer what kind of entity you spawn by the type of the def itself

#

theres a lot of things you can also add to the class, that are specific for handling that type of entity

#

you use type system to bind a runtime entity to the def type, it is very clear and simple to use

rotund horizon
#

DOTS Best practice

timber flame
plucky laurel
#

you can figure it out as you develop, data is serialized by property name, so it doesnt matter if you move some field in the base class, it will be preserved

#

even when you remove the property for the type it still hangs around in the .asset

jagged fiber
#

Hey guys! A small shader question.

I have a vertex function where I set UV.
That UV goes to the fragment function.

The question:
I'm reading a book where it says "vertex function data goes straight into the fragment function".

Is it really true? Why, then, in the fragment function I get hundreds of different UV values for each pixel, while having just 3 vertices (meaning I set UV data just 3 times in the vertex function).

Some interpolation happens in-between to get per-pixel UV and probably some other calculations.
Where can I read about what happens in-between vertex and fragment functions?

regal lava
#

Probably get some better answers there

drifting vessel
#

Does anyone here have experience with asynchrony? Specifically, trying to make REST API calls, so I don't want it locking the main thread.

urban trellis
#

UnityWebRequest is asynchronous

bleak citrus
#

where did this quote come from?

#

well, two staff members said it's under the same license as the engine

#

so there's your answer

drifting vessel
upbeat path
#

did you not see '/Il2CppOutputProject' this includes the output from IL2CPP not IL2CPP itself

#

pretty sure that's just support code for the runtime

#

build your own il2cpp project and look at the code generated

untold basalt
#

Hey folks! I’m trying to make a Camera move using DOTS but it’s not working, and I’d like to understand why. I have a MovableComponent (just a tag) and a pretty small system:

{
    protected override void OnUpdate()
    {
        Entities.ForEach((ref LocalTransform transform, in MovableComponent _) =>
        {
            transform.Position += new float3(5f, 0, 0) * SystemAPI.Time.DeltaTime;
        }).Run();
    }
}

I attached the MovableComponent to the main camera and to a cube. The cube moves, but the camera doesn’t, even if I can see the camera localTransform being updated in the inspector, which makes me think I’m missing something. I also tried making the camera a child of an empty game object and adding the tag to the GO instead, but it doesn’t work either.

Of course, I could just use Camera.main.transform.Translate, but I want to understand why it's not working. I searched everywhere but I couldn’t find an answer. Any ideas?

sand wraith
#

In unity some in built components like "Transform","Rigidbody" etc can be added only once to an object.
I am going through components of a gameobject runtime and if the components can be added only once, i should ignore that..
for custom components i can check if it has [DisallowMultipleComponent] attribute and ignore. But for built in components, it not possible..
Is there a way to detect it for built in components?

#

anyone?

spiral swift
#

I have a classification model that takes 3 values

#

not sure how to get the output tho

#
        InputTensor[0] = Kills;
        InputTensor[1] = Hits;
        InputTensor[2] = Distance;
        Worker.Execute(InputTensor);

        Tensor outputTensor = Worker.PeekOutput();
        return int.Parse(outputTensor.ToString());```
#

this is what I did for the output, but it gave me an error

sand wraith
long ivy
sand wraith
#

actually do we have an official list of components that can be added only once? couldn't find one in docuumentation. This was my first approach to the problem

long ivy
#

probably not, but it wouldn't be hard to write a little editor script that tries to do just that and have it generate that list for you

sand wraith
#

ok

#

a warning dialogue box is popping up when i try to add one of those exceptions.. so unity is detecting it somehow..

timber flame
# plucky laurel you can figure it out as you develop, data is serialized by property name, so it...
public class Building: ScriptableObject{
  //name, id, icon, description
  public IRequirement[] Requirements;  // preconditions and requirements to be able to construct it
  public IEffector[] Effectors;
  
}

It is neat and really flexible but probably over generalized.
Sometimes, one specific effector is just for one specific type of building. Also, about requirement.
I mean it is hard to use some of them more than one time.
It reduces code duplication (e.g. implement an effector or requirement just one time)

The alternative way is to define properties one by one in each building type. It can cause duplication.

public class Building: ScriptableObject
{
}
public class PlantDefinition: Building
{
   public ElementData RequiredWater; // required
   public ElementData RequiredSoil; // required
   public SeedData Seed;  // required

   public bool CanFertilize;
   public ElementData Fertilizer;  //optional requirement
   public int BuilderLevel;  //requirement
   public Season PlantSeason;    // requirement

   public ProductData Product;  // product id and amount  // effector
   //-------------------------
   //????
   public Season HarvestSeason;
   public float GrowRate; // grow rate per cycle
   //...
}

sleek marsh
#

u mispelled ProductData

severe topaz
obtuse arch
# timber flame ```cs public class Building: ScriptableObject{ //name, id, icon, description ...

everything has its pros and cons, Every-time you will face a scenario where a practice or principle is regarded as decent one but will not be applicable to your design. Forcefully applying it the greatest mistake one can make.
First and foremost finalize on design rather than hopping from one req to other, Then architect your codebase according to the expected axis of changes keeping in mind the domains where frequent changes are required and what makes it easy to reduce production time and helps you ship quickly.
Each decision to make a code/module accessible for design will eat up tiny part performance somewhere or will introduce an overhead which is unavoidable. In short there is no fixed design. Build Test Refactor is the way to go. Fixating on a principle/design/architecture is the worst thing you can do at early stage of development similarly as optimizing prematurely.

timber flame
severe topaz
#

@timber flame that doesn't mean it's the best solution for your problem though. and you don't know if its' devs ever felt like they majorly fucked up with tech debt.

#

i'd be more interested in how games like path of exile handle their stuff because it doesn't look like they locked themselves in with any gear at all

timber flame
#

I think in cult of the lamb, they have used same approach, define all fields in one class.

#

like defining them in a table (db)

severe topaz
#

if we take path of exile as an example, every item that is not a currency (e.g. armor, weapons and flasks) is essentially treated the same. almost none of them behave the same, except that they all have similar rules for how currency is used on them and how crafting works on them.
that's why IMO it's a good example of how modular stuff should work.
if you already know exactly what you want and it doesn't need this much flexibility, and you're not planning to expand, then do whatever you want tbh 🤷‍♂️

#

even then they probably curse at themselves for the spaghetti they made daily

regal lava
#

im convinced POE is all spaghetti considering how that game performs

#

but that's probably because the bloat of affixes and statistical stuff that's been being crammed into their calculations over the years

severe topaz
#

@regal lava yeah, too much pointless crap that is barely noticeable anyway. the only way to gain performance is to kill faster so that there are less calculations to perform.

#

but the modularity is 👌

cobalt hemlock
#

Hey guys, i am loading some data from a database. There is a line in the code that assigns a boolean value to isOn for a toggle (Please see attached).

When happens, it triggers a ArgumentException: Object of type 'UnityEngine.Object' cannot be converted to type 'UnityEngine.GameObject'.... exception, which when I look at the step through has nothing to do with my code after the boolean is assigned.

If i comment it out, all works fine.

Please see the attached images. If you need any more information let me know.

dusty wigeon
upbeat path
cobalt hemlock
dusty wigeon
#

Readying a bit, it might be cause by UnityEvents that are not properly set.

#

What the Event on the Toggle looks like ?

cobalt hemlock
dusty wigeon
#

Maybe, I would try to remove the Events and see if it works.

sly grove
#

Actually seems like an object is trying to be passed to the toggle listener as a parameter that is supposed to be a GameObject but is not

#

I'd scour your toggle inspectors

#

Basically a wrong object is set as the parameter or something of that nature

cobalt hemlock
#

This is how the Toggle is setup.

dusty wigeon
#

The None could be the cause.

cobalt hemlock
sly grove
#

Could be yes

#

BTW if you want to toggle your toggle in code without triggering the listeners, it has a SetWithoutNotify function you can call instead

cobalt hemlock
#

Yup, i completly missed that...I checked the logo one, but not the dimension one. Apologies. Thanks for the help, I do i appreciate it.

cobalt hemlock
cobalt hemlock
worthy lodge
raw lily
#

Is there a difference between changing the localScale of a transform, that contains a sprite renderer OR changing the .size of a sprite renderer?

sly grove
#

Read the docs for .size

#

it's not what you wan't in 99% of circumstances

#

the difference, obviously, is that one changes the object's scale and the other doesn't

#

meaning its children will also be affected etc

raw lily
sly grove
#

Mao answered you

#

Also Carwash's answer was also an answer of sorts

raw lily
#

Yeah, it tends to be obscure whether my UI is actual UI or 3D in my project, I don't think I should use an Image there but will see if there are any upsides I might I've missed the first time I decided on SpriteRenderer.

sly grove
#

SR is not a UI element

#

if you are making UI, don't use a SpriteRenderer

solid lodge
#

public class BuildingSystem : MonoBehaviour
{
    public GameObject[] placeableObjects;
    public float placementHeight = 0f; // The desired Y position for object placement
    public float movementMultiplier = 1f; // Multiplier for cursor movement distance

    private void Update()
    {
        HandleInput();
    }

    private void HandleInput()
    {
        for (int i = 0; i < placeableObjects.Length; i++)
        {
            if (Input.GetKeyDown((i + 1).ToString()))
            {
                PlaceObject(i);
                break;
            }
        }
    }

    private void PlaceObject(int index)
    {
        GameObject objectToPlace = placeableObjects[index];

        Vector3 mousePosition = Input.mousePosition;
        mousePosition.z = -Camera.main.transform.position.z;
        Vector3 worldPosition = Camera.main.ScreenToWorldPoint(mousePosition);
        worldPosition.y = placementHeight; // Set the Y-position to the desired placement height

        Vector3 objectPosition = new Vector3(
            worldPosition.x * movementMultiplier, // Adjust the X-axis position
            worldPosition.y,
            -worldPosition.z * movementMultiplier // Invert the Z-axis position
        );

        Instantiate(objectToPlace, objectPosition, Quaternion.identity);
    }
}

So what the code should do is place a object depending what key I press and it kinda does it

  1. when placing on the x axis it goes the other way the mouse is
  2. the objects dont place exactly where the mouse it instead it bundles up together kinda (Tried to fix this using movement multiplayer)
#

what are the steps to fixing this?

#

photo of what i mean bundling up

prime kite
#

i have a 2d world made of chunks

#

each chunk contains 10x10 square objects (every time i move in a direction i instantiate 3 chunks and destroy 3 chunks)

#

instantiate is really slow

#

do you guys know what the besy way to optimize this is?

tiny pewter
#

object pool
but this cost lots of ram of your machine since it has to hold the object cant be free()ed in heap

dusty wigeon
#

It does not cause that much of strain on memory because GameObject and component are relatively small. (The asset (Texture, Audio, Meshes) are most of the time what is the cost)

#

In theory, the user could even reuse the same object without needing additional objects as he destroy others.

vestal condor
#

running into this issue where a collider is being shown as existing in editor but actually doesn't exist in code

i was working with a prefab variant that previously had its collider removed
i updated it to be no longer removed, and indeed, instantiating it shows that it is no longer removed

but it's literally acting like it's not there - i can't even collide with it despite all the layers being correct

I've run into a similar issue before where i was colliding with a non-existing collider after removing it (and verifying that it is indeed not there in editor)

#

anyone has any clue why this happens? deleting all my streaming assets and restarting editor doesn't seem to help

#

its like the editor and game are desynced

radiant oasis
#

hey who needs help

vestal condor
#

nvm restarting machine seems to have worked

#

just a super weird bug with unity editor

timber flame
#

To show stats easily, do you have something like below for each definitions?

  // AttributeType contains all attributes (enum or a collection of strings)

  // A definition (character, building, etc.)
  public override Attribute[] GetAttributes(){
     return new Attribute[]
        {
          new Attribute(AttributeType.Power,power)
          //...
        };
  }

or instead of define properties as primitive types with values, define them as Attribute type.

public class BuildingA: ScriptableObject{
    public int HitPoint;
    //...
}
public class BuildingA: ScriptableObject{
    public Attribute HitPoint;
    //...
}
[Serializable]
public class Attribute{
    public AttributeType Type; // or directly AttributeDefinition
    public int Value;
}

[Serializable]
public class AttributeDefinition: ScriptableObject{
    public AttributeType Type;
    public string Name;
    public Sprite Icon;
}
tender ore
#

Unity randomly micro freezes, Profiler shows editor loop 98% at this moment, what can I do? Tried different 2022+ versions

sly grove
#

it won't be there in the build

#

most of the time, it's not worth worrying about

remote drift
#

Is there any publicly (or internally) accessible method to convert instance ID to Object?

#

Specifically I want that for Material

flint sage
#

Nope

remote drift
#

😩

dusty wigeon
novel plinth
#

never really used it, but the Playables api uses that like everywhere

remote drift
novel plinth
#

oh.. then idk about that 😄

#

never really used it in such manner

dusty wigeon
remote drift
#

allthough

#

that ExposedReference might be it (or not)

novel plinth
#

it should, if you just want to look for the reference to the object directly

#

the rest is up to your impl

dusty wigeon
#

Also, can you just use directly a reference ?

remote drift
#

in the end I will use it obviously

#

but the whole setup for usage I want to be burst compiled

#

(decals rendering)

dusty wigeon
#

So, you cannot pass a pointer to an object ?

#

🤔

tiny pewter
#

Need Fixed until the job is end

remote drift
#

anything that is GC managed is not burst compatible

dusty wigeon
remote drift
#

no

dusty wigeon
#

Like I said, I never done burst, so I do not know. But I feel like using GetInstanceID is definitely the worst way.

remote drift
#

nah, it is the way to go for a lot of API

#

I was surprised to see that Unity NavMesh api accepts instance ID

#

which allowed me to set the field via ptr

#

I really wish there was a way to make draw calls natively via instance ids

#

or maybe some wrapper for it

#

which has set/get property with actual reference, while storing object as instance id

#

(this is how NavMeshBuildSource type works)

novel plinth
#

@remote drift if you don't mind with reflection at all, there's protected api iirc called FindObjectFromInstanceID

remote drift
#

🤔

novel plinth
#

it's under UnityEngine.Object

remote drift
#

I'd love to avoid indirection

#

nope

#

ExposedReference is not it

novel plinth
#

not quite sure what you mean by that, you wont see anything there as this is resolved internally

remote drift
#

it has managed field

#

that struct is managed

#

thus - not burst compatible

#

(besides, it's unclear what's it used for even)

valid tapir
#

Hi, Is there a faster way to get Layer Index of Mesh Renderer, I have about 19k of them and I want to sort them by layer which on PC takes about 4ms, 3ms when I pass data to the JobSystem, and do the comparison there, the 2.79ms is spent on getting gameObject.layer. I can't pre cache this because the parts of a scene are being loaded and unloaded outside of my scope as Scenes.

sly grove
#

crosspost^

candid meteor
#

sorry

opaque elbow
#

Hi, I'm having an issue with implementing the IEqualityComparer interface, I have the following unit test, when I try and run it with the comparer the test fails, but when I try to compare each memeber individually without using the comparer the test fails.

    
    public class SaveData
    {
        class GameDataComparer : IEqualityComparer<GameData>
        {
            public bool Equals(GameData x, GameData y)
            {
                if (ReferenceEquals(x, y)) return true;
                if (ReferenceEquals(x, null)) return false;
                if (ReferenceEquals(y, null)) return false;
                return x.gold == y.gold && x.howardCoins == y.howardCoins;
            }

            public int GetHashCode(GameData obj)
            {
                return HashCode.Combine(obj.gold, obj.howardCoins);
            }
        }
        
        [UnityTest]
        public IEnumerator SaveSystemTest()
        {
            var gameObject = new GameObject();
            gameObject.AddComponent<DataPersistenceManager>();
            var saveDataTest = gameObject.AddComponent<SaveDataTest>();
            var gameDataComparer = new GameDataComparer();

            yield return new WaitForSeconds(1f);
            
            
            DataPersistenceManager.instance.fileName = "unit_test.save";
            DataPersistenceManager.instance.NewGame();
            DataPersistenceManager.instance.SaveGame();
            DataPersistenceManager.instance.LoadGame();
            
            GameData data = new GameData();
            data.gold = 999;
            data.howardCoins = 999;

            Assert.AreEqual(data, saveDataTest.data, "Saved game data isn't correctly loaded", gameDataComparer);
        }```
sly grove
#

it's going to test object equality by looking at the GameData class.

#

If that class implements IEquatable, it will use that

#

otherwise it will use .Equals

#

which by default checks for reference equality

#

oh wait - sorry I just noticed you passed in gameDataComparer as a parameter to AreEquals 🤔

#

Is that actually a thing??

scenic forge
sly grove
opaque elbow
sly grove
#

So ... it's failing in both cases?

opaque elbow
#

sorry typo

opaque elbow
#

the test is passes when not using the comparer

scenic forge
#

You can't mutate records, but you can create a new record based on existing one:

var newSaveData = oldSaveData with { gold = newGold };
opaque elbow
sly grove
#

Can you show the code?

#

also have you taken any debugging steps?

#

Debug.Logs etc?

opaque elbow
#
[UnityTest]
        public IEnumerator SaveSystemTest()
        {
            var gameObject = new GameObject();
            gameObject.AddComponent<DataPersistenceManager>();
            var saveDataTest = gameObject.AddComponent<SaveDataTest>();
            var gameDataComparer = new GameDataComparer();

            yield return new WaitForSeconds(1f);
            
            
            DataPersistenceManager.instance.fileName = "unit_test.save";
            DataPersistenceManager.instance.NewGame();
            DataPersistenceManager.instance.SaveGame();
            DataPersistenceManager.instance.LoadGame();
            
            GameData data = new GameData();
            data.gold = 999;
            data.howardCoins = 999;

            Assert.AreEqual(data.gold, saveDataTest.data.gold, "Saved game data isn't correctly loaded");
        }
scenic forge
rancid kite
#

Hellooo

#

Finally i find here yepp

opaque elbow
#

Also I have an interface so objects can modify data

rancid kite
#

Ops sorry here is advanced

opaque elbow
midnight vale
#

Hi folks. I have two sprites with polygon colliders attached to them and I need them to detect a mouse hover. If these two sprites overlap is there anyway to "order" them so that a raycast from the mouse position will hit the topmost poly?

#

Both are in the same layer btw

opaque elbow
sly grove
#

Also you should/could use the event system for this

#

instead of doing a manual raycast

#

IPointerEnterHandler

scenic forge
midnight vale
#

@sly grove Alright. Thanks I'll look into that 🙂

opaque elbow
midnight vale
#

How would you implement an event system for that, like you mentioned?

sly grove
#

i.e. 2d sort order and render order

#

you don't implement the event system

#

you use Unity's existing event system

midnight vale
#

You mean IPointerEnterHandler?

sly grove
midnight vale
#

Ok now I get it. Thanks 🙂

opaque elbow
#

thanks

sly grove
#

right that's kinda what I was hinting at originally...

#

or implementing the IEquatable interface

opaque elbow
#

Idk why unity suggests doing it the other way arround if it isn't going to work XD

scenic forge
# opaque elbow Idk why unity suggests doing it the other way arround if it isn't going to work ...

Ah, for completeness, here's a reference implementation for value semantics:

public class Stuff : IEquatable<Stuff>
{
    public string Foo { get; set; }
    public string Bar { get; set; }

    public bool Equals(Stuff other) => other is not null && Foo == other.Foo && Bar == other.Bar;

    public override bool Equals(object obj) => Equals(obj as Stuff);

    public override int GetHashCode() => (Foo, Bar).GetHashCode();

    public static bool operator ==(Stuff lhs, Stuff rhs) => Equals(lhs, rhs);

    public static bool operator !=(Stuff lhs, Stuff rhs) => !(lhs == rhs);
}
grim dew
#

Is anyone here familiar with unitys extension of statemachinebehaviours SceneLinkedSMB? Stumbled across a video that uses it to make a state machine for AI and would like to implement it in my game as well, but I have some questions about. Would love to pick someones brain on it who's familiar with it. https://www.youtube.com/watch?v=vxgxcDihld4&ab_channel=DapperDino is the video I found it from and here's the pastebin of the script: https://pastebin.com/zP9s2y8p

Help to support the channel if you are feeling super kind: https://www.patreon.com/dapperdino

Join our Discord: https://discord.gg/sn9xXK4

https://www.youtube.com/watch?v=raQ3iHhE_Kk
https://www.youtube.com/watch?v=6vmRwLYWNRo

Here is Unity's own state machine behaviour extension script: https://pastebin.com/zP9s2y8p

In this video I show yo...

▶ Play video
plain granite
#

is there any alternative for TypeCache.GetFieldsWithAttribute that i can use at runtime? i have a script that replaces the value of all fields that have a specific attribute, but because TypeCache is only available in the editor, i can't use it in a build

compact ingot
# grim dew Is anyone here familiar with unitys extension of statemachinebehaviours SceneLi...

(maybe more of an opinion and not quite an answer) personally i'd make a state machine specific to my system's needs (may have multiple FSM implementations specialized to those), i'd skip the visual editor for anything that doesn't absolutely need it (terrible debug experience). If i need a visual behaviour editor i'd use Node Canvas (AssetStore). A FSM imo shines especially in two situations: either you want to view all the transition rules on one "page" in code for the ultimate separation of transitions from the effects of those transitions, or you want to securely encapsulate state's implementation into separate files/classes with lots of padding and contracts that get discussed extensively in meetings. IMO the best go-to/default FSM to start with is this adaptation of stateless for unity which can be used to implement arbitrarily complex systems, it does allocate on each transition so it's not ideal for being called each tick on many agents but one can easily adapt it to be non-allocating: https://openupm.com/packages/games.corundum.stateless-for-unity/
The core of such a declarative FSM engine can be implemented with maybe 500 lines of code.

grim dew
compact ingot
grim dew
compact ingot
dusty wigeon
# grim dew Is anyone here familiar with unitys extension of statemachinebehaviours SceneLi...

Having done a small amount of PlayerController, I can guarantee you that not every Animation State result in an state of your player and not every state of your player result in an Animation State. By example, you might have a Fall animation and a Fall High animation. I also suspect that you will have issues with transition/responsiveness due to the blending of the StateMachine; Something you do not need/want in the actual state of your Character.

While it seem like a good idea at the moment, those disparity will cause you a headache on the long run. That being said, I still use those StateMachineBehaviour to synchronize the Animator and the StateMachine of the character whenever it is necessary.

bleak citrus
steel snow
#

can unity's jobs use delegates ?

olive python
#

I split screen dynamically at runtime so there is ghosting sometimes. How do I refresh unity rendering

sage radish
#

They didn't mention they were using ECS.

real blaze
thorn flintBOT
#

You can format your multiline code block with C# highlighting! Just add cs to the start of it. Highlighting example below!

class Fluffs : FluffyCat
{
    public void PetCat ()
    {
        Debug.Log ("Petting Cat.")
    }
}
regal olive
#
foreach (KeyCode kcode in Enum.GetValues(typeof(KeyCode)))
        {
            if (Input.GetKey(kcode))
                Debug.Log("KeyCode down: " + kcode);
        }
#

i've got this code here cuz i need to detect what key the player presses (i want custom keybinds but i don't want to have an extremely long scroll menu). tho whenever i press a button from the gamepad it records smth like this. i'd like it to record only JoystickButton9, not Joystick1Button9

unreal charm
#

Need help with making the enemy ai use the same bullet controller the player is using

bleak citrus
#

don't crosspost in every channel at once.

unreal charm
real blaze
regal olive
ebon walrus
#

Just saw there there is a networking channel under simulation - moving the question there.

white seal
#

Hello all! Was curious if anyone knew if Scene.GetRootGameObjects is guaranteed to be in the same order as the hierarchy?

#

The docs unfortunately don't show this to be the case but wasn't sure if it wasn't documented or if it's just not guaranteed.

vale zenith
#

I am a bit confused how to properly 'instantiate' a prefab via Resources.Load(). Right now I'm essentially doing the below, and it returns a value, however I don't see the prefab appear in my hierarchy in the editor. Do I have to call Instantiate() on myObject or do anything else?
GameObject myobject = Resources.Load(path) as GameObject;

austere jewel
kindred tusk
#

If I have a class like this:

[Serializable]
class Foo { public int X; }
class Bar : MonoBehaviour {
  public Foo foo = new();
}

will there be an extra allocation of Foo before deseriaization when the constructor is called internally? Or will the instance created with new() be deserialized into by Unity?

#

e.g. if serialization is:

_foo: 5

Will the instantiation logic be?

_foo = new();
_foo = new() { X = 5 };

or:

_foo = new();
_foo.X = 5;
hushed fable
kindred tusk
potent shoal
#

Greetings, I created a diagram to hopefully help explain my perspective.
I am trying to create an ability in my game that causes my velocity driven player controller to latch onto the closest object, and then maintain it's distance while moving around that object with a line renderer attached from the player to the object.
While moving around the target object, the player will be moving at it's original speed, but for each rotation around the object, the player speed will increase, to eventually create a sling shot effect.

#

Here are two representations. I want the distance the player is to the object to remain the same for the entire duration of the ability, but consistantly move the player around, rotating in a forwards direction.

#

Hoping for any ideas. Thank you!

tiny pewter
#

https://en.m.wikipedia.org/wiki/Gravity_assist
Similar to this but much complicated
Since you require maintain the same radius while rotation and increasing the velocity that means the acceleration needed to be increased during the trip, and the problem is when to stop the increasing of acceleration (gravity) so the object can be launched

A gravity assist, gravity assist maneuver, swing-by, or generally a gravitational slingshot in orbital mechanics, is a type of spaceflight flyby which makes use of the relative movement (e.g. orbit around the Sun) and gravity of a planet or other astronomical object to alter the path and speed of a spacecraft, typically to save propellant and r...

granite finch
#

Can't really contribute much other than ask question. But... does the prefab look correct if you just drag it into the scene by itself?

oblique field
pulsar isle
#

What are some use cases for Unity Native (c++ dlls) ?

#

Could a project benefit in speed or other metrics if someparts of the code are used from a native plugin ?

dusty wigeon
pulsar isle
#

Yeah you are right ! But could be there performance improvements when translating a C# piece of code in C++. I know the l2cpp thing makes it almost C++ like in performance but I'm just wondering and trying to learn.

pulsar isle
#

Even in the context of C# code being compiled to C++ via l2cpp ?

#

Interesting ! Thanks for the paper.

dusty wigeon
#

Whenever you want to optimize something, you need to profile before hand.

novel plinth
#

one simple example such as virtual calls

dusty wigeon
#

Also, note that IL2CPP is not an optimization pass. It is mandatory for some platform.

pulsar isle
#

Yeah I'm so clueless about compilers and all these, just curious so if you have any helpful regarding articles, sources etc I could learn a lot without bugging you.

dusty wigeon
#

If you want to learn more about compiler in general, you should try to learn assembly.

pulsar isle
#

I found this too, @dusty wigeon Thanks for the suggestions !

dusty wigeon
#

There is also University Course

#

Also, you should definitely look into Burst as it is the standard for optimized code in Unity. @pulsar isle

sand wraith
#

I want create an empty gameobject during editor play mode. Is there any way to make that gamobject stay in scene even after i exit playmode?

#

anyone?

tiny pewter
#

the only way i know is copy the GO in play mode and paste it in edit(?) mode

novel plinth
#

thus we have edit and play modes

hybrid gale
# regal olive ```cs foreach (KeyCode kcode in Enum.GetValues(typeof(KeyCode))) { ...

hi ! i am using Input system to read input values of a controler.
so i did it with a PS controler, and it does nice.
and i wanted to do it with a friend Xbox controler, so Unity has recnized the controler, but Input system wont listen to any input of the Xbox controler.
So, is it possible to use 2 differents controler with Input action ?

hybrid gale
#

it doesn't work even if i use 2 files

tawny sand
#

i have a rigidbody2d which i'd like to smoothly move to a very specific location
i would like to use addforce for this (to avoid the physics engine disembowling me) but am not sure on how to find the right amount of force to add over a certain period of time, as I would like to smoothly deaccelerate the rigidbody as it gets closer to its stopping point
Any help would be very appreciated. Thanks!

sly grove
tawny sand
#

PraetorBlue is typing....

#

oh no

#

ok so i looked it u

#

*up

sly grove
# tawny sand a... what?

It's basically how things like cruise control in your car work, and industrial robot arm controllers, drones, etc... You plug in your desired variables (position, speed) and the thing is constantly checking it scurrent state vs the desired state, the error in the variables, and adjusting etc to achieve what it wants
https://en.wikipedia.org/wiki/PID_controller

tawny sand
sly grove
#

software engineer

tawny sand
#

is game dev a side gig?

#

it shows lmao

#

in a good way

#

because jeesus christ

patent bear
#

Is there any way to set up a SpriteRenderer to use submeshes and different materials? I am familiar with Sprite.OverrideGeometry but I'd like to create two meshes where one is opaque and one is transparent without needing to move everything to MeshRenderer, if possible.

raw lily
#

I have a script I got from Github that works fine, but only when the GameObject is selected in inspector. For that reason the script does not work in a build, any idea what could cause a weird behaviour like this?

austere jewel
raw lily
thin citrus
#

Hi. I need to do cutscene sequence in my turn base game. For example, move the camera, play shoot animation on character, play hit on character target, display hit damage, etc. I think Timeline is a good candidate but my first impression is it look like it is better for predefined cutscenes then runtime one.

For example, I want to apply the previous sequence on any character, the shoot animation is different per character, the camera should be on the side with clear view, etc. I know you can make custom clip but I wanted to know if it is worth going into this rabbit hole or not. I want to be able to easily modify the sequence without the need of code. I am open to any alternative if you have one

brittle dove
#

I have this error that wont tell me what script it is from. All I know is everytime I swap data in a field in my inspector I get this bug. It didn't happen until I upgraded from Unity 2021.3 to Unity 2022.3

ArgumentNullException: Value cannot be null.
Parameter name: _unity_self
UnityEditor.SerializedObject.FindProperty (System.String propertyPath) (at <ac87b54e58ee4be198261fd5c8030d52>:0)
UnityEditor.UIElements.Bindings.SerializedObjectBindingContext.BindPropertyRelative (UnityEngine.UIElements.IBindable field, UnityEditor.SerializedProperty parentProperty) (at <9f0f853070524c139e10a85a1cfcedb6>:0)
UnityEditor.UIElements.Bindings.SerializedObjectBindingContext.BindTree (UnityEngine.UIElements.VisualElement element, UnityEditor.SerializedProperty parentProperty) (at <9f0f853070524c139e10a85a1cfcedb6>:0)
UnityEditor.UIElements.Bindings.SerializedObjectBindingContext.ContinueBinding (UnityEngine.UIElements.VisualElement element, UnityEditor.SerializedProperty parentProperty) (at <9f0f853070524c139e10a85a1cfcedb6>:0)
UnityEditor.UIElements.Bindings.DefaultSerializedObjectBindingImplementation+BindingRequest.Bind (UnityEngine.UIElements.VisualElement element) (at <9f0f853070524c139e10a85a1cfcedb6>:0)
UnityEngine.UIElements.VisualTreeBindingsUpdater.Update () (at <735c071c072642ad8d077fa38c650a28>:0)
UnityEngine.UIElements.VisualTreeUpdater.UpdateVisualTreePhase (UnityEngine.UIElements.VisualTreeUpdatePhase phase) (at <735c071c072642ad8d077fa38c650a28>:0)
UnityEngine.UIElements.Panel.UpdateBindings () (at <735c071c072642ad8d077fa38c650a28>:0)
UnityEngine.UIElements.UIElementsUtility.UnityEngine.UIElements.IUIElementsUtility.UpdateSchedulers () (at <735c071c072642ad8d077fa38c650a28>:0)
UnityEngine.UIElements.UIEventRegistration.UpdateSchedulers () (at <735c071c072642ad8d077fa38c650a28>:0)
UnityEditor.RetainedMode.UpdateSchedulers () (at <9f0f853070524c139e10a85a1cfcedb6>:0)
brittle dove
#

Reverted back to my backup gonna test in 2021.3 tomorrow and see if that error keeps happening.

random dust
#

When you don't see where code comes fromon the stacktrace, it is compiled and no real trace exists. This either happends because it's not your code, or you are playing in a build

#

In this case, it appears to be a Unity bug

#

So changing Unity versions could fix it

wide loom
#

I'm generating a world layout on a 2D grid. I'm using a L-Systems to generate a road layout (green tiles) And then putting buildings around the roads. Now I want to divide the grid up into "Towns" based on the clustering of populated cells. I think I need to feed the Vector2Int[] array of populated (roads and buildings) cells into a Cluster analysis function; but this is where I'm lost.

#

Does anyone know of a library that would be appropriate for creating the cluster boxes?

upbeat path
wide loom
dusty wigeon
pliant hawk
#

Hello everyone,

Im currently working on a windows exe. where 1 user can controll inputs with touch or mouse, while a second user can conect via a XR HMD. You can think of it as a local multiplayer (its not but you get the idea).
I have done this before, last time with:
Unity 2021.3.11f1 / OpenXR 1.4.2 / Interaction Toolkit 2.0.4

since its a HDRP project i chose to update for this one to a newer Unity version because of all the Raytracing Performance increases.

The current project is with:
Unity 2022.2.15f1 / OpenXR 1.7.0 / Toolkit 2.3.1

The setup im running is one complete XR rig, with handtracking and controller other than very similiar in the general structure to the "Complete XR Origin Hands Set Up" that is part of the interaction toolkit. So only one "MainCamera" rendering to screen 1, with depth 0

The second user, the 2D user has an individual player manager with a seperate camera, also rendering to screen 1

Now as soon as i disconnect the headset my FPS drop from around 89 to 3, and the main change i can see is that the "XR.Display.PopulateNextFrameDesc250.18ms" increases by this amount.

I tryed detecting the disconnection from the HMD but i can only detect its connection not the disconnection. I think that there is something still trying to access the HMD even after it beeing disconnected.
I tryed this the following 2 ways:

    void OnDeviceChanged(UnityEngine.InputSystem.InputDevice device, InputDeviceChange change)

    if (device is UnityEngine.InputSystem.XR.XRHMD && change == InputDeviceChange.Added)
#

Aswell as with the new input system with a HMD action as a Button with "isTracked[OpenXr HMD] binding properties

Either way i cant get e message when the HMD disconnects.
As far as testing goes, there seems to be a problem with me having 2 cameras rendering to screen 1. As soon as i dont use a second camera the fps dont drop. But i do get the same result if i add a Canvas ScreenSpace that renders to screen 1.

Maybe someone has a idea what could cause this behaviour or some recomandations on how to properly use a multi camera setup for VR and a windows touch/mouse user.
Thanks in advance!

brittle dove
brittle dove
#

And also this is Editor only atm since I haven't done any build with this new project.

storm tartan
#

can someone throw me some document and tutorials about setting a runtime database? It has to be a safe one, the player should not be able to send&change data without the permission of the database's controller.

#

currently I am using google runtime database, but the player is able to change the data anytime he want to

#

so there is supposed to be a controller/confirmer in the middle of runtime - client connection

#

how can I do that in unity and google runtime database concepts?

#

any recommendations are welcome

sly grove
#

it should be connecting to some web application you control (which enforces authentication/authorization of requests) and the web app is the thing that talks to the DB

#

though I do think something like Firebase might have document-level auth built in such that a player can only modify his own document.

storm tartan
#

what is it called?

sly grove
#

Well there are about 39840912312 different ways to make a web application

#

pretty much every programming language has dozens of frameworks for it

#

so... it kinda depends on what you're comfortable with

#

or want to learn

#

(note that a web application is not the same as a web_site_)

delicate perch
#

Web application made using emoji programming language

limpid pagoda
#

i know i can insert functions as part of my animation
however can i do that as part of an animation's (a state's) transition to another?

i have some interruptions set up
is there a way for me to call a function once the mid point of the transition has taken place?

at the moment when i press LMB down a transition, which happens to take a whole second, takes it from state A to state B.
if i release LMB at any moment, though, the transition inverts, and the animation walks back to A.
how can i call a function (only) if more than 50% of the transition has happened?

long ivy
#

sounds like a job for StateMachineBehaviour

#

assuming you don't want the more direct route of just checking the animator state on mouse release

limpid pagoda
#

i'll take anything
i know such fine control would require diving deeper
i just don't know where to start
i read the reference but it feels like some terms aren't sufficiently explained

#

is StateMachineBehaviour the guy responsible for blending the animations along the transition?

long ivy
#

it's a scriptable object that receives messages when animator state changes

#

you could do fancy things with it sure, but you probably just want to create one that checks the animator state and if it meets your condition, looks at the Animator's GO and calls a method on some script on that GO

dusty wigeon
#

If you really want fine tuning, you can use Playable instead of an Animator.

#

Howerver, i doubt your issue cannot be solve by an other approach.

limpid pagoda
#

holding LMB starts opening a "mouth" (transition from closed to open which are animations with 1 single frame)
release LMB before 50% transition = transition back to closed
release LMB after 50% transition = transition to bite animation instead

dusty wigeon
#

Also, is it skinned ?

limpid pagoda
#

that's actually a valid idea

#

what's skinned in this context?

dusty wigeon
#

Skinned Mesh

limpid pagoda
#

simple 2d image with no mesh

dusty wigeon
#

If there is a small amount of animation data, you could do it by code.

long ivy
#

I would examine the animator state directly for that case and decide which parameter to set on the state machine based on your condition instead of trying to do something fancy

dusty wigeon
#

If this is trully a major part of your game, you can read the animation manually.

#

It won't be performant, but if you have nothing else going it can do the job.

limpid pagoda
dusty wigeon
#

Also, how are you animating the 2D image ?

#

Is it a sequence of image ?

#

Like a spreatsheet ?

limpid pagoda
#

it's all rotations of the image, on the animation clip's curve

dusty wigeon
#

It is only rotation ?

limpid pagoda
#

i have one image
and an "animation clip" with one frame, which has it rotated to a certain value

#

open = 0 rotation
closed = 90 rotation for example

dusty wigeon
#

100% do it through code.

limpid pagoda
#

the animation is actually the transition between those two "frozen" states

dusty wigeon
#

Your use case is not made for the Animator.

limpid pagoda
#

yeah i guess i more or less suspeced that

dusty wigeon
#

You could even use things like DoTween.

limpid pagoda
# long ivy I would examine the animator state directly for that case and decide which param...

hold LMB, trigger on, scythesclosed -> scythesopen
i have some "interrupts" on (decided to check it when i saw it and it turns out it does exactly what i thought it'd do - allows transition to quit midway)
release LMB goes back.
but is it actually possible to make it "go back" to a different animation (cleave instead of close - say if i turn a trigger on) with the default statemachinebehaviour?

#

the following question would be how to bind the release of a button to the action map in order to check for how much of the transition has taken place

dusty wigeon
limpid pagoda
#

kind of

#

it's basically, open less than 50% and release, back to closed state
open more than 50% and release = cleave

#

dude chatgpt is nuts lol
tells me stuff about how transitions and triggers work better than unity reference

dusty wigeon
#

Because, the tradionnal way of doing animation is (In, Strike, Out) or (In, Loop, Strike/Out).

limpid pagoda
#

yeah i'll need to study some of the elements i'm already using (without fully understanding) before proceedign

#

i just learned a trigger is NOT reset if the transition is interrupted

dusty wigeon
#

I have done some charge abilities and it works well with looping animation.

limpid pagoda
#

i'll probably need some finer control regardless because the outcome of the "cleave" will depend on the timing (how much it opened, how long it stayed 100% open before the cleave happened etc)

dusty wigeon
#

Just use the animation lenght

limpid pagoda
#

thanks for the tips

#

i definitely need to read more

dusty wigeon
#

It seem that you try to make your logic inside the Animator while it jobs is to animate.

dire viper
#

Hello guys, I am facing some big performances issues when launching my game. The start menu is starting fine but when clicking the play button, the game takes 30s to start :/ Any idea ? I start to look at the profiler but couldn't understand it so far.
You can find the profiler screen shot attached.

#

I see APplication.Preload.Asset, is it the Resources.Load that I am doing to generate my object in my scenes that takes so many times ?

#

Which is weird is that the first scene is really slow and the one after are direct :/

sly grove
dire viper
#

That ?

#

It seems that it loads all the music 😮

sly grove
#

Switch from Timeline view to Hierarchy view

sly grove
# dire viper

although yes this does seem to show you are reading a bunch of files

#

whatever this preload assets thing is

dire viper
#

It would totally make sense if it was that, it would explain why it's slow for the load of scene 1

#

Looks like we have something there 😄

limpid pagoda
#

in regards to double tap:

if i have one action mapped to single click
and another, different action mapped to double click (0.75s max time between clicks is the default)

will the first action (single click) only execute 0.75s after the first click (in order to make sure it's not going to be a double click)?

sly grove
#

If you want to do that kind of exclusive handling you may need to write some code yourself

limpid pagoda
sly grove
#

Already responded

austere garnet
#

Hi, I'm looking for any better solution/workaround to this issue I experience constantly with Visual Studio on Mac:

When I create or rename a script file in the VS editor, I'll often see an error similar to this when I try to compile:

CSC: Error CS2001: Source file '/path/to/project/Assets/Scripts/SomeFolder/NewClass.cs' could not be found. (CS2001) (Assembly-CSharp)
The only way I've found to resolve this is to open unity and select Unity -> Preferences -> Regenerate project files. Is there any way avoid this or to fix it from within VS instead?

#

this seems to happen because VS creates a new empty file with the name NewClass.cs; the error happens after I've renamed it (on VS Windows, creating a new file opens a dialog, which gets saved with the name I give it)

upbeat path
austere garnet
#

weird, this happens even when I don't have the editor open

placid shell
#

is there any easy way to copy read only MeshData into the writeable MeshData? (guessing using unsafe utilities perhaps?)

obtuse arch
#

Incase there is a build target mismatch the shaders will result render in error mode, For eg if you built for android and ran them on windows, The shaders wont work since they are built for android. Make sure the execution mode is set to 'Use AssetDatabase' instead of 'Simulate Groups'

finite swan
#

Texture2D.GetRawTextureData() is returning a byte length of 0, even though i can happily pass the texture to a shader and it can read it just fine.

I use Texture2D.CreateExternalTexture(...) to create the texture, calling a Native Rendering Plugin I wrote that reads BMP files:

// Creates BMP
extern "C" UNITY_INTERFACE_EXPORT void* CreateTexture2DFromBmpFile(const char* file, int* width, int* height, int* status) {
    
    // Read the BMP
    bmpread_t bmp;
    auto bmp_res = bmpread(file, BMPREAD_ALPHA | BMPREAD_BYTE_ALIGN | BMPREAD_ANY_SIZE, &bmp);
    if (bmp_res == 0) { // Failed to load the image
        *status = bmp_res;
        return nullptr;
    }

    *width = bmp.width;
    *height = bmp.height;

    // Generate the DX13 texture
    ID3D11Texture2D* mPtr;
    D3D11_TEXTURE2D_DESC textureDesc;
    ZeroMemory(&textureDesc, sizeof(textureDesc));
    textureDesc.Width = bmp.width;
    textureDesc.Height = bmp.height;
    textureDesc.MipLevels = 1;
    textureDesc.ArraySize = 1;
    textureDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
    textureDesc.SampleDesc.Count = 1;
    textureDesc.Usage = D3D11_USAGE_DEFAULT;
    textureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
    textureDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
    textureDesc.MiscFlags = 0;

    D3D11_SUBRESOURCE_DATA subres;
    subres.pSysMem = bmp.data;
    subres.SysMemPitch = bmp.width * 4;
    subres.SysMemSlicePitch = 0; // Not needed since this is a 2d texture

    auto tex_res = g_D3D11Device->CreateTexture2D(&textureDesc, &subres, &mPtr);
    if (tex_res != S_OK) { // Failed to create the texture
        *status = tex_res;
        return nullptr;
    }

    // Clear the memory and return
    bmpread_free(&bmp);
    return mPtr;
}

what am i doing wrong here? I've tried setting the CPUAccessFlags to CPU_ACCESS_READ but that didnt change anything.

stuck onyx
#

Hello people!
I want to do something very simple, when i collide with an object i want to take it's material and fade it.
I know i just have to get the component MeshRenderer and do what i want with the material but I remember there was a tricky thing when doing this, like the material was duplicated or something, could someone point me where this 'tricky' thing was and how to solve it please?

#

materialPropertyBlock was the answer, although not sure if its worth it for just 1 material?

tall ferry
stuck onyx
#

yeah but if we do that lots of times dozens or hundreds of materials will be dupli-triplicated

#

so i guess the only thing to do was to kill the duplicated material once im done with it?

#

(destroy) ?

tall ferry
#

if you need to destroy the actual object afterwards then do so, i dont know what functionality u are going for

#

u shouldnt worry about pre-optimizing this unless you've already tried and noticed some performance issue with the simple solution. Also, MaterialPropertyBlock says

Note that this is not compatible with SRP Batcher. Using this in the Universal Render Pipeline (URP), High Definition Render Pipeline (HDRP) or a custom render pipeline based on the Scriptable Render Pipeline (SRP) will likely result in a drop in performance.
https://docs.unity3d.com/ScriptReference/MaterialPropertyBlock.html

stuck onyx
#

no i dont have to destroy the object, the only thing i want is fade to transparent an object im crossing

#

this is how i did it:

tall ferry
#

how does this even run?

#

am i blind or is this not 2 infinite loops

flint sage
#

It is

stuck onyx
#

yes

#

2 infinite loops

#

🤣

flint sage
#

You're not actually modifying alpha

#

And you probably want a delay each loop

stuck onyx
#

true, should use a coroutine

tall ferry
#

either way though, is directly modifying the material even going to be an issue. Are u really going to have thousands of these objects just chilling around invisible?

stuck onyx
#

no, actually not, im going to do a tween with the material and f*it

scenic gulch
#

hey, does anybody know of a good resource to learn about how to do

#

whoops!

#

how to USE the jobs system with animations? I am looking to optimize our management game that has a few hundred NPCs

#

I think that is what I need to be doing, but can't find much in the way of guidance of how to actually implement it

brave cairn
finite swan
brave cairn
finite swan
vestal condor
#

hmm, just updated unity from 2021.3 to 2022.3 and i'm getting this error, no clue why
I've rebuilt my streaming assets as well, no clue what's throwing this error

DamageFactory is a scriptable object and i see that my scriptable objects are still intact in my project browser

fresh salmon
vestal condor
#

Yup, it's certainly matching

#

It only broke after updating to 2022

#

I'm not sure why it's throwing the warning, especially since existing scriptable objects are certainly working

fresh salmon
#

I'd say ignore these, if it didn't break anything

vestal condor
#

Well there's like 500 of those

upbeat path
vestal condor
#

happens whenever i enter play mode

#

i’m reimporting the entire project to see if it does anything

upbeat path
vestal condor
#

is anyone familiar with this problem?

#

im running into it again and i really have no clue how to fix it without reimporting the entire project, which i just did...

plucky laurel
#

Splash Screen [Title] is not in the build settings

spare sentinel
#

Hi. I have a mfps package and the mobile control addons fire button just fires. And it is really anoying that you need to aim with your other finger. Most fps games gave the fire button functionality, that if you hold it, it shoots and also if you move your finger, it aims. So I tried to modify the script for mobile control addon, but made it so if you with EVERY BUTTON. And also the buttons do not work. Just aim. Can anyone please look into my script, specifically onto InFireClicked function and tell me what could be wrong?
https://gdl.space/amapahuxaf.cs

Thank you so much 🙂

plucky trellis
# tawny sand i have a rigidbody2d which i'd like to smoothly move to a very specific location...

A good way to do this for games is to some some kind of second order equations. This video is how I learned about it. It's a bit heavy on math, but he does give example code. https://youtu.be/KPoeNZZ6H4s

It's been a while since the last video hasn't it? I've made quite a bit of progress since the last update, and since one of the things I worked on was some procedurally animated characters, I decided to make a video about the subject. In particular, this video highlights the entire process from initial motivation, to the technical design, techni...

▶ Play video
bleak citrus
#

Good ol’ diff eq

#

I learned that back in my freshman year of college. Been a hot minute

onyx blade
#

Is it redundant to specify OnMouseEnter, OnMouseExit etc on an abstract class given they are event functions provided on MB?
I'm thinking I could specify it since most children will define those functions, but im not sure if all of them have to.
I hesitate because I don't currently have functionality for those functions in the abstract base class

#

the question rly is, is there a point in defineing them? does it matter at all given the compiler will probably strip them out if they are empty?

sly grove
#

it will actually just hurt performance, forcing an empty method to run

onyx blade
#

I figured, I will remove the implementation in the base class for now.
if I end up with a situation where I do have functionality in that base class,
I can add it there and override the function, then call its base

plucky laurel
#

can also be solved compositionally, component that catches OnMouse and relays to target component through interface

#

no idea why

onyx blade
#

the OnMouse functionality is part of the monobehaviour though.
interfaces cannot inherit as far i am aware

#

unless I am mistaken

plucky laurel
#

components are monos for all intents i dont think you can directly inherit component without unity throwing, point is you dont always have to shove everything in mega sandbox base

onyx blade
#

ah, then I misunderstood

#

you meant different components on the object relaying information between each other.
I read interface and assumed you meant the datatype

plucky laurel
#

yes, this is an idiotic example because all monobs will catch Mouse events, but for example IOnMouse.. you yourself declare, target types implement and relay invokes when needed, it is very useful in various places but its mostly between game objects

#

anyway, dont use OnMouse

onyx blade
#

the logic is solid, altho it would indeed be a weird usecase talking about the mouse events in MB's

plucky laurel
#

use event system IPointerEnter etc

onyx blade
plucky laurel
#

what happens?

#

Physics Raycaster present on camera?

onyx blade
#
public abstract class Interactable : SerializedMonoBehaviour, IPointerEnterHandler
{
    public void OnPointerEnter(PointerEventData eventData)
    {
        Debug.Log("HI");
    }
}```
plucky laurel
#

and all layers setup properly?

onyx blade
plucky laurel
#

event system present in the scene?

onyx blade
#

that's the one

#

I dont have one in my scene, cuz im usign the other input system and didnt have UI yet

plucky laurel
#

it works in tandem with ui, you wont click through it like with OnMouse

onyx blade
#

I plan to do all the input from input actions myself

onyx blade
plucky laurel
#

parameter on raycaster

#

OnMouse you mean? i dont know i used it a long time ago

#

you have zero control over it

#

with event system you have its full source

onyx blade
#

I was about to say

plucky laurel
#

you can do whatever you want

onyx blade
#

that is quite a bit more convenient if im honest

#

more control is always better

#

and since the pointerevents are interfaces I can implement them in the base or its children depending on where I need them

plucky laurel
#

yes

#

ill send you some code

onyx blade
#

that leaves me with th equestion why you would want to use the system I was using 🤔

plucky laurel
#

what do you mean

onyx blade
#

well. the method you described seems much more elegant and easier to use cuz of the flexibility

plucky laurel
#

OnMouse is legacy

onyx blade
#

which makes me question what the purpose is in having both systems exist

#

ah

#

that'll do it

plucky laurel
#

shouldnt have been there in the first place

#

like a lot of other baggage

onyx blade
#

there are quite a few things like that in the engine either way

#

some legacy, some unfinished

#

personally, I am referring to the many itterations of node stuff in the editor

plucky laurel
#

my favorite is - magic methods, properties on Component, BroadcastMessage, blackbox animator, general naming of things like Random/Debug

#

everyone is stuck with magic methods because at some point unity supported 3 languages

onyx blade
#

I tihnk I found 4 different node code-bases in the editor while I was crafting our state machine

plucky laurel
#

which ones?

onyx blade
#

and all of them had their own annoying bugs

plucky laurel
#

animator sm i know

onyx blade
#

I used XNode (tho thats a 3rd party one), the one from Bolt,
then there is the shadergraph api and amother one I forgot the name of

#

the last one was highly experimental and only exists on a git repo

#

cant even find it anymore, been a while

plucky laurel
#

xnode and bolt use imgui afaik

#

i dont know how people work with it

onyx blade
#

its weird, I worked with it for a day or 2 and just ew

#

the shadergraph api is quite nice, but it has a lot of setup

plucky laurel
#

it lags that the biggest downside, its made so badly compared to something like dearimgui its laughable

#

shadergraph at least is retained

#

so you can have thousand nodes and its fine, but the feel of it, the design is bad

onyx blade
#

ya it doesnt feel great

#

I remember one of the api's for nodes was super laggy when you wanted to drag

#

either a node or panning the screen

#

it was shitting itself

plucky laurel
#

yeah unity imgui is not made for that, you can squeeze everything out of it with your own optimizations, like doing manual bvh, swithing to Repaint event, not using layout at all, hiding any property fields , culling

#

i just hope dearimgui will be ported to editor by some genius

#

some day i dont want to use uitk and manage retained objects

onyx blade
#

uitk is quite nice to work, it's much better compared to the other systems once I got the hang of it

#

some things work, others are lacking. but most things work well enough to build on top of

finite swan
# brave cairn What do you mean by "Any recommended staging ?" Staging resources allowed to be ...

Hey, i have tried it and unity giving me an error now.
d3d11: failed to create 2D texture shader resource view id=1007 [D3D error was 80070057]

From my research, it seems this is a invalid argument. All i did was change the Usage to USAGE_STAGING.

I tried:

  • change CPUAccessFlags to D3D11_CPU_ACCESS_READ
  • BindFlags to 0, D3D11_BIND_SHADER_RESOURCE, D3D11_BIND_CONSTANT_BUFFER
  • Format to sRGB (DXGI_FORMAT_R8G8B8A8_UNORM_SRGB)

None of these worked and all threw the same error.

// CreateTexture2DFromBmpFile loads a bitmap from a file and stores it in a new Texture2D, returning the pointer of the texture.
extern "C" UNITY_INTERFACE_EXPORT void* CreateTexture2DFromBmpFile(const char* file, int* width, int* height, int* status) {
    
    // Read the BMP
    bmpread_t bmp;
    auto bmp_res = bmpread(file, BMPREAD_ALPHA | BMPREAD_BYTE_ALIGN | BMPREAD_ANY_SIZE, &bmp);
    if (bmp_res == 0) { // Failed to load the image
        *status = bmp_res;
        return nullptr;
    }

    *width = bmp.width;
    *height = bmp.height;

    // Generate the DX13 texture
    ID3D11Texture2D* mPtr;
    D3D11_TEXTURE2D_DESC textureDesc;
    ZeroMemory(&textureDesc, sizeof(textureDesc));
    textureDesc.Width = bmp.width;
    textureDesc.Height = bmp.height;
    textureDesc.MipLevels = 1;
    textureDesc.ArraySize = 1;
    textureDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB;
    textureDesc.SampleDesc.Count = 1;
    textureDesc.Usage = D3D11_USAGE_STAGING;
    textureDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
    textureDesc.BindFlags = 0;
    textureDesc.MiscFlags = 0;

    D3D11_SUBRESOURCE_DATA subres;
    subres.pSysMem = bmp.data;
    subres.SysMemPitch = bmp.width * 4;
    subres.SysMemSlicePitch = 0; // Not needed since this is a 2d texture

    auto tex_res = g_D3D11Device->CreateTexture2D(&textureDesc, &subres, &mPtr);
    if (tex_res != S_OK) { // Failed to create the texture
        *status = tex_res;
        return nullptr;
    }

    // Clear the memory and return
    bmpread_free(&bmp);
    return mPtr;
}
raw lily
#

Hi, I'm duplicating a terrain at runtime, to a new GameObject, but it doesn't seem like I'm able to apply deformations to that new terrain at runtime, any idea what's wrong and how to work around it?

slim crater
#

Hi, I have a Unity game where I am using adressables (loacally), when I build for Android all work fine and adressables are loaded, but on IOS they are not loaded. Online I found a lot of people with this same problem but nobody found a solution to overcome the problem, is there someone that know how to solve this issue?

thorn narwhal
icy smelt
#

You guys know if IL2CPP is compatible with the Roslyn API?

sly grove
midnight mural
#

Hi, this code works perfectly fine in the unity editor environment but doesn't work on a windows build, any ideas why? Thanks: https://hastebin.com/share/gebohihife.csharp

icy smelt
sly grove
midnight mural
#

The build crashes when the function is called but in the editor it works fine

#

The error Im getting is a null reference exception, a gameobject is missing, by some reason, when value B is a null gameobject it is assigning value A for some reason, this happens just in the build in the editor it works fine

sly grove
#

for example some variable you are depending on is not yet initialized due to script execution happening in a different order

regal olive
#

Should I use System.Net.Http.HttpClient from inside C# Jobs?

#

Moreover, my understanding is a job cannot work with a long-lived mutable object outside of it as it's not inherently thread-safe. Should I just create and dispose multiple clients inside the job in this case?

umbral trail
scenic forge
#

And lots of async options like UniTask or good old coroutines.

vestal condor
#

strange question but any idea why clicking "use null comparison" doesn't do anything? this warning is quite annoying to fix one by one

#

pressing "fix all occurences in document" doesnt actually do anything

#

is there some plugin i'm missing in my visual studio or something?

#

i'm pretty sure i have visual studio tools for unity installed

fresh salmon
# vestal condor i'm pretty sure i have visual studio tools for unity installed

Pretty sure it's the code fix that comes with the analyzer that's broken. Indeed you shouldn't use ?. because that ignores the "destroyed but not null yet" state of unity objects (it'll end up calling the method even if the script was destroyed, throwing an exception).
It'll most likely fix the code into

if (pressActivateActions)
  pressActivateActions.SetOwner(owner);
vestal condor
#

Yup, I know that the code fix is broken

#

I'm wondering how to make the code fix not broken, because this particular thing is quite annoying to fix manually

fresh salmon
#

See if the Visual Studio Editor package in the the Package Manager can be updated

vestal condor
#

basically I'm doing some code cleanup and noticed a lot of these and it would be preferable if I didn't have to fix them individually

fresh salmon
#

Other than that, you could use VS's search & replace that works with the full regex specification (yes, even capture groups and replacement values) to fix that in one go

vestal condor
#

hm yea, I'm familiar with regex but I was hoping to avoid doing it lol

dull kestrel
upbeat path
regal olive
scenic forge
dull kestrel
scenic forge
#

That’s not true, UWR can run in a coroutine without blocking the main game loop.

dull kestrel
#

Perhaps in a Task/Thread.

scenic forge
#

Stuffs like IO whether it’s disk or network are like that.

dull kestrel
dusty wigeon
#

It will run on the same thread, we agree on that.

scenic forge
dull kestrel
dusty wigeon
dull kestrel
#

If that's your stance though, you can recommend IEnumators/IEnumerables.

scenic forge
#

Disk and network isn’t, they are usually just CPU telling disk “ok go grab this file for me, and call me back when you are done” and CPU is free to do other things in the meantime, such as continuing the game loop.

drifting vessel
#

Does anyone know if Array.FindAll is fast, or should I implement my own algo? Iterating through hundreds of values.

austere jewel
small latch
#

Makes a new list and array 😔

austere jewel
#

Dictionary, Hashset, whatever, it's unclear what you're trying to do

drifting vessel
scenic forge
#

Hundreds is tiny number for modern computers unless you are doing this enough for performance to matter, and at that point the allocation is probably what’s hurting more.

#

And as usual with performance, always benchmark first before stabbing at code blind.

fresh verge
#

How safe is it to do this inside a coroutine?

Time.deltaTime;
yield return new WaitForEndOfFrame();

Aka, will delta time return the expect values?

sly grove
fresh verge
#

I am aware

sly grove
#

the second line - you want yield return null if you just want to wait one frame

fresh verge
sly grove
#

yield break; would quit the coroutine

fresh verge
#

ah, sorry, missread

#

So, yield return null is what I would use to go to the next frame instead of wait for end of frame?

#

"go"

austere jewel
#

There is no 'go', there is only waiting

#

WaitForEndOfFrame is almost never what you want to use

#

yielding null will make execution return to that point on the next frame

fresh verge
#

Huh, I wonder why it's null instead of something like "WaitForUpdate"

austere jewel
#

So it doesn't allocate anything

fresh verge
#

Make sense

mellow sail
#

Do you guys know anyways to disable drag and drop feature on list using Odin Inspector, so if I drag a game object into the list in inspector, it wont be added?

mellow sail
#

Well i could but the thing is, i need the object in those list to be costumizeable (Inline Editor) but i just wanted for the list to be not able to drag and drop

#

So when using the tool i build, people would not accidentaly added an object in the list

#

but could still added an object that are already in the list for the object that is intended using a button

#

so read only is not an option

#

never mind, found it

#

found another way around

regal olive
#

hey yall how do i lerp a color to transparent? ive been stumped on how to use lerp for 2 days including today now

#

i have a scene variable set for color, from there i grabbed the material color for the asset i want to use for the variable, i called that objecta so thatd go to lerp a<-, b, t, right? so whats the line to set the alpha for objecta to 0 then apply it to b

#

do i need to create a second variable and basically set alpha to 0 for the second color variable? if so how do i go about doing that, and if not, what do I do for b on lerp?

#

thanks

tall ferry
#

your alpha value is between 0 and 1, not 255 incase you were using that

regal olive
#

im think i should create a variable for the instiante and set the material for that, does that sound right

tall ferry
#

doesnt matter where the object comes from, as long as you have a reference to it. Then you just grab the renderer's material, and update the material.color with whatever you want

regal olive
#

ahhh ok ok, ill need to adjust the renderer of the asset the instiante grabs to the new color is what ure saying ok got it

#

thanks

tall ferry
regal olive
tall ferry
#

hopefully u already have a shader for this, because changing the alpha on the regular opaque shaders do nothing

regal olive
#

idk what that means, im more of a hands on learner so once i get to that bridge and unity stops returning errors then ill try to look into that before i ask wtf does that mean lmao

tall ferry
#

unsure if this is different in other render pipelines, i know almost nothing about graphics.
But theres a few workarounds, like using surface type - transparent or writing a custom shader.
Transparent is kinda weird if your object has any unique shape because it doesnt write to depth and can render inside of itself then

#

now that its on transparent, its gone

regal olive
#

ah ok i just need to change the surface type to transparent. sounds good, ill remember to do that

quartz gulch
#

Hey all - so I have a webgl project (2022.2) where I have several scenes bundled as asset bundles and I'm loading each one depending on which is needed - this is working great with one issue.

It seems that baked NavMeshes aren't exported with my scene in the asset bundle which means that when I load the scene there's no NavMesh. I've been thinking up solutions and I could either generate the NavMesh at runtime (not a fan of this solution as WebGL is extremely CPU limited and I'd rather do it offline). Instead I want to serialize the NavMesh and store the data in a gameobject, then deserialize this data at runtime to recreate the NavMesh. Is this something which is doable? Should I just bite the bullet and generate at runtime?

I can't seem to find a good way to do this from my brief experiment, if anyone could point me in the right direction or tell me if this solution is not the way to go I would appreciate it

tropic stag
#

I'm struggling with "active ragdolls" for a while now. Anyone have some pointer on how to loop through character joints and create configurable joints from them to match the 2 axis and limits?

The ragdoll builder works, but uses character joints, and I'd like to have the configurable ones to apply "drive".

misty glade
flint sage
#

If you're using it for game code, you don't really have to worry about it

real hazel
#

I am calling this every fixed frame to detect collisions at really high speeds and I seemingly have to use raycast all to check collisions since the raycast hits the projectile. I do not know much about performance but I am pretty sure sorting an array every physics frame is bad. Is there another way around this?

        float distance = direction.magnitude + 0.2f;

        RaycastHit[] hits;
        hits = Physics.RaycastAll(lastPos, transform.forward, distance);
        System.Array.Sort(hits,(a, b) =>(a.distance.CompareTo(b.distance)));

        foreach (RaycastHit hit in hits)
        {
            GameObject hitObj = hit.collider.gameObject;
            Vector3 hitPos = hit.point;
            Vector3 hitRot = hit.normal;

            if (transform.GetComponent<Collider>() != null)
                if (hit.collider == transform.GetComponent<Collider>()) continue;

            activeProjectile = false;
            OnHit(hitObj, hitPos, hitRot);
            transform.position = hitPos;
                
            break;
            }
        }
        lastPos = tip.position;
dull kestrel
real hazel
#

some projectiles will need a collider and some projectiles will need to collide with eachother

dusty wigeon
misty glade
#

The problem with that sentence is the API has an override that takes FindObjectsInactive.Include

dusty wigeon
#

It still says that it does not return Asset.

#

I do not know what could be an UnityEngine.Object if it is not an Asset or an instance in a scene.

#

Every time I used it I had no issue. I used: FindObjectOfType

misty glade
#

the autodocs indicate it does find inactive objects:

#

FindObjectOfType is slow - even FindFirstObjectByType is documented as slow

dusty wigeon
#

Yeah, not an issue on an Awake.

#

If you use it with care*

#

So the issue, is that it find disabled object ?

#

I though you were asking about if it was only object in the scene.

misty glade
#

It's all good - I've got a workaround solution for now, just saving a reference to the object. I'm using it to find a "fader" when transitioning between scenes, and the component is disabled until it's needed, but I needed a way to find it. It's also fine since I'm only calling this once between scene transitions

dusty wigeon
scenic forge
#

In 2D, let's say I have a massive amount of static objects and their bounding boxes, and I also have a dynamic moving view box. What's the best way to store these objects' bounding boxes, so that I can efficiently query which ones overlap with the view box?

#

Oh I'd like to implement this on my own, not using Unity stuffs.

scenic forge
tall ferry
sly grove
plucky laurel
scenic forge
#

Good insights thanks, I'll think about it.

tropic stag
# tall ferry You should just go through the process of deleting the joints manually and makin...

But the ragdoll helper sets up the character joints with sensible axis limits, I was hoping I can copy those limits over to a corresponding configurable joint... I also saw someone on the internet say they didn't replace the joints but added configurable ones, leaving the character ones to limit motion, and adding freemoving configurable ones to use the drives... but that seems wrong to me somehow?

scenic forge
plucky laurel
#

i suggest looking at github for any quadtree implementation using bounds

scenic forge
tall ferry
plucky laurel
#

its octree but its a good example of both approaches

scenic forge
#

Yeah, reading both repos atm 👍

plucky laurel
#

there is a simple approach with spatial hashing grid

#

easier to write, faster inserts

#

but unless you make it hierarchical you will have fixed size buckets which can be undesired depending on scenario

scenic forge
#

Yeah I don't know how close or far apart object boxes are.

plucky laurel
#

you have zooming?

scenic forge
#

Hmm unsure but unlikely, what are you going to suggest?

plucky laurel
#

problem with fixed buckets is that if you zoom out you get massive amount of buckets to query and you cant predict or find the golden balance of bucket size

#

but if amount of buckets at any point queried is invariant, no zoom, then its easy to estimate

#

for example it can be 1/4 of camera frustum

#

so you end up with max of 4-6-8 buckets on screen at any point

#

can go lower/higher to find best performance, since biggest impact is not from bucket iterations but overlap/distance tests per object

scenic forge
#

I see, I'll read up on spatial hashing grid as well.

tropic stag
tall ferry
dusty wigeon
tall ferry
# tropic stag copy what? I've been fiddling with this for a while, and I don't like setting th...

i also didnt really like how setting up the axis were, but its just something you'll be fiddling with for awhile. Even with gizmos i found it extremely hard to visualize where the limits truly were. Theres a reason not too many games use real active ragdolls as their main character. Even on discussion forms, one commonly linked video goes into active ragdolls but the guy uses animations to drive the positions, so its not even an active ragdoll basically lol.

tropic stag
#

I'll give it another shot. I was also reading the famous ConfigurableJoint extension code everyone links and it specifically "reprojects" the bone rotation to a coordsystem built from the configurable joint axis, so in theory the axis don't HAVE to match, but I can't get it to work so I'm thinking it would probably be better if they do match...

tall ferry
tropic stag
#

also.. slerpDrive.mode = JointDriveMode.Position; this makes me question why position and not rotation, but trying to look, the docs say that the jointdrivemode is obsolete, so perhaps there's some new line needed to properly configure the joints

tall ferry
#

Yea i dont remember slerp drive having a mode option

#

I dont really know if you'll be able to use those extensions. Theres really no reason you cant just set the motion to all locked, angular motion to limited in the inspector. id only really take parts of that code if you were dynamically creating them, but thatd be a real challenge

#

Honestly all I did was setup a copy of the character to run via animation, then my character copies the animators rotations only and it works quite well. You just want to make sure you calculate the rotation as an offset from the original animator rotation. The extension code somewhat has this formula already, but for the hips (or whatever you use as the center of mass), you'll have to adjust it to not copy the Y rotation

tropic stag
tall ferry
# tropic stag thanks, before manually replacing the joints you used unity's ragdoll helper rig...

i did use the ragdoll helper but that was purely just to get the colliders and rigidbodies premade. For the drives, you'll just need to really experiment. I set all my character weights to 1 so my drives arent even ideal/cant be used on a character where the weights are set to match real world weights. I might adjust it but definitely not rn.
Honestly I dont know if theres a major difference between slerp or x + yz, i dont notice any. X + yz just lets u separate the X out to have a different force, no clue why they dont separate yz as well.
Slerp applies the same drive to all 3 axis

bleak citrus
#

i keep getting really close to implementing a quadtree/octree

bleak citrus
rotund tendon
#

Hello, I am overriding the GameObject's transform position(because have a script simulating custom physics for it), but I want to be able to drag the gameobject in the editor, but since the position is overridden by my physics, trying to drag the gameobject with the move tool in the editor doesn't work, the object's position is locked.

Is there a way to get the event or value of the editor's move tool if the user drags and moves it by one of the axes? (so then I can add that to my physics object's position)
Thanks

dusty wigeon
rotund tendon
forest jacinth
#

Is there a way to create a "slow motion" sphere that would.. put enemies in slow motion without affecting the entire game and the player? God of War had such an effect when dodging at the right timing with a certain item equipped.

boreal jasper
#

Procedural animation for a crab with Rigging animation & Inverse kinematic

dusty wigeon
nova summit
#

How can I apply a rotation in world space to a transform of a humanoid character? Is it possible to get a identity values for a transform in humanoid character so that I can apply the rotations easily?
I want to consider default idle position as the reference pose.

dull kestrel
nova summit
#

Well this is what I have.

  1. I know which points in object space where I can place each joint of a character
  2. I calculated the angles for each bone so that I can apply at the joint transform of humanoid character
  3. But the problem is the joint transform may have some offset and setting it to identity doesn't match the idle pose (consider idle pose is something like looking forward and hands, feed downward direction) - Consider this with hands down https://media.sketchfab.com/models/82f155b2abe142df9e0600ce3d006a80/thumbnails/4502258dace64d759f73d83fdb85f99f/757707edab6a44b3859087ae30e98cad.jpeg
dusty wigeon
regal olive
forest jacinth
nova summit
dusty wigeon
forest jacinth
#

a wut

mellow sail
#

its a plugin, library etc whatever you call. Basically you could control time flow in easier way without hard coding (using Unity,Time)

#

just look it up

#

you can make a sphere time zone too just like you wanted

#

its a built in method in chronos

#

Well the bad news you couldnt find it in unity asset anymore, but as jack sparrow said "A life of a pirate". You could still search it in web

forest jacinth
mellow sail
#

yup

forest jacinth
#

noice

mellow sail
#

its OP trust me

#

just put your head more in the documentation

scenic forge
#

@plucky laurel Continuing the conversation of quadtree from last time, if I'm understanding correctly, the idea is that for objects whose bounding boxes don't entirely contained in a node's children, they are added to the node itself instead.
That got me thinking about what you said about zooming, since in my case zooming is irrelevant, does that mean instead of constructing the quadtree top down, I could choose "1/2 view box width and height (or 1/4 view box area)" as the size of leaf, and construct the quadtree bottom up?
This has the issue that scene size may not be powers of 2 of the leaf size, which I don't believe is a required property for quadtree to work, right?
And lastly, is there a general rule of thumb for choosing the size of the leaf, assuming that most objects are: 1) way smaller than the view box size and 2) more or less evenly distributed throughout the scene?

next sluice
#

Guys i need help, how can i place a GameObject on a hexagonal grid via script?
Thank you in advance

sly grove
#

which can be configured to use a hex grid

next sluice
#

oh, i was thinking something more like the GameObject brush

#

Thanks

sly grove
#

you asked for "via script" so I figured you meant in code

#

if you mean makijng an in-game brush at runtime, then what I said before is how you'd do it

next sluice
#

@sly grove so i have a slight issue, i have a normal hexagonal tile grid, and when i put this normal grid, it doesnt line up

next sluice
#

thought it would be more complicated than that KEKW

fickle sapphire
#

I have an object with a character controller component that moves to a target position (represented as the red gizmo sphere). This object has a movement vector given in local space using animation curves to apply root motion during an animation, such as a dodge. I have purposefully made the object's position lag behind the target position to an extra extent to debug this.

My question is about rotation. I have a movement vector, represented in local space, but because we already have a target position, we want to move the object toward that target position, using the movement vector. If I didn't have a target position, I would simply just do the following:
movement = transform.rotation * movement;
This would convert the movement to world space and allow me to use it in the CharacterController.Move() method.

However, because I have a target position, I need to change the rotation to ignore the object's current rotation (it can change during the movement), and rotate the movement vector to reach the target position.

dusty wigeon
dusty wigeon
#

This is the same principle as if you were using a ViewDirection. Not exactly sure what is the formula from the top of my head.

#

Something like Quaternion.LookRotation(target position.xz - character position.xz, Vector3.up) * movement.xz.

misty glade
#

I'm looking to do a drag and drop arrow thing in UI space, and sorta stumped with some angle/quaternion stuff.

I've implemented IPointerDown, Up, and Drag handlers, and I instantiate my prefab using the eventData.position at the start. While dragging, my intent was to update the arrow with a method called SetDrag(Vector2 from, Vector2 to). When I try to calculate the Quaternion using Quaternion.FromToRotation, I'm getting odd values. Do I need to cast my Vector2s to Vector3s manually?

#

(without any rotation currently)

dusty wigeon
#

Your vector is already been cast

fresh salmon
#

Can you try with Quaternion.LookRotation(to - from) instead? This rotates on Z so you might need to pass a Vector3.forward as argument 2

misty glade
#

Sure, standby

fickle sapphire
#

movement = Quaternion.LookRotation(networkTransform.currentPosition - networkTransform.transform.position, Vector3.up) * movement;

misty glade
fresh salmon
#

Yours

dusty wigeon
misty glade
#

two Quaternion questions at the same time :p

fickle sapphire
fickle sapphire
dusty wigeon
#

Remove the y value

fickle sapphire
#

yeah I gotcha

fresh salmon
misty glade
# fresh salmon Yours

Hm, closer. I can probably use this but I'm not understanding the output. In terms of "clock positions" - 3 o'clock (oc) is 0 degrees, noon is 90 degrees, 9oc goes back down to 0 degrees, but 6oc is 270

#

so the only values i get are 0-90 and 270-360

#

I mean maybe this is fine.. lemme just slap it on the gameobject and yolo-see what happens

#

yolo yo-came and yo-went without effect

misty glade
#

When you say set the .right or .up directly - do you mean edit the prefab so it's facing the correct way? ie, using the uh.. red arrow (I think) for .right?

#

(I probably ought to flip the asset around as well - it currently points left by default so I have to flip it manually)

fresh salmon
#

Nah that's fine, the arrow is pointing left but no problem, you can still set its transform.right to the reversed direction vector instead

#

Since transform.left isn't a thing

fickle sapphire
# dusty wigeon Remove the y value

Same problem here, I did try this in the past and it didn't seem to work


Quaternion targetRotation = Quaternion.LookRotation(new Vector3(networkTransform.currentPosition.x, 0,                              networkTransform.currentPosition.z) - new Vector3(networkTransform.transform.position.x, 0, networkTransform.transform.position.z), Vector3.up);

horizontalMovement = targetRotation * horizontalMovement;

movement.x = horizontalMovement.x;
movement.z = horizontalMovement.z;```
misty glade
#

i'll just manually figure out the flippy flippy

#

quaternions make my brain hurt

fickle sapphire
#

dw they made my brain hurt when I first started too

#

well actually they still make my brain hurt

fresh salmon
#

Yeah it's inverted, just have to slap a * -1 somewhere

dull kestrel
#

To me you just wanna get the mouses world position and then set the transform.right to that direction and skip all the rotations (if I understand what you're trying)

misty glade
#

i'm just experimenting because i'm too dumb to math it out

fresh salmon
#

The direction you're constructing from to and from, does it work if you reverse them in the subtraction?

#

(a - b instead of b - a)

#

Hm wait no, it's not entirely reversed, it's mirrored on the Y axis

#

Saw the video again

#

And then mirrored on X at some point? Wtf is going on here

dusty wigeon
#

@fickle sapphire Is it what you want ?

public class Movement : MonoBehaviour
{
    [SerializeField] private Transform target = null;
    [SerializeField] private float speed = 0.0f;

    private void Update()
    {
        float vertical = Input.GetAxisRaw("Vertical");
        float horizontal = Input.GetAxisRaw("Horizontal");

        Vector3 direction = target.position - transform.position;
        direction.y = 0;
        direction.Normalize();

        transform.position += Quaternion.LookRotation(direction) * new Vector3(horizontal, 0, vertical) * Time.deltaTime * speed;
    }
}
misty glade
#

wait that's wrong, standby

sand acorn
#

Hello there, I assume this is sort of a newbie question, I have a parallel job where I am doing some calculations and right now I am refactoring my code to modify a struct value; The problem right now is that I have some conditionals on my job and in those I want to modify a value inside my struct at the current index, but for some reason the struct does not change at the specified index unless I call the function outside of those conditionals, what am I doing wrong? I assume the problem relies on the index differences, like blockBack can happen at index 0, 20, 24 and so forth

 //back
            if (blockBack == 0)
            {
             //Does not work
                AssignData(index, blockPos, BackFace);
            }

            //front
            if (blockFront == 0)
            {
                 //Does not work
                AssignData(index, blockPos, FrontFace);
            }

//Does work outside of conditions
 AssignData(index, blockPos, BackFace);

  private void AssignData (int index, half3 blockPos, NativeArray<half3> face)
    {
        _VertexData[index] = new VertexData
        {
            Position = AddQuad(blockPos, face),
            index = index,
            //  Normal = _VertexData[index].Normal,
            //  Uv = velocityPosition.Uv,
            // Tangent = velocityPosition.Tangent
        };
    }

#

I have used debug log on the conditions and they do happen

#

This is the AddQuad function if it helps

 private half3 AddQuad (half3 blockPosition, NativeArray<half3> vertexPositions)
    {
        half3 outValue = half3.zero;
        for (ushort i = 0; i < vertexPositions.Length; i++)
        {
            half3 vert = vertexPositions[i];
            outValue = new half3(math.half(vert.x + blockPosition.x), math.half(vert.y + blockPosition.y), math.half(vert.z + blockPosition.z));
        }

        return outValue;
    }
#

I highly doubt that function fails because it does log a result

dusty wigeon
#

I guess we can simply though

fickle sapphire
#

Which cube is the target?

dusty wigeon
#

There is a cube turning around an other

#

When it does a circle, it is when I press left or right arrow.

fickle sapphire
#

right so, that seems fine. However, my problem is that when I apply the rotation that would usually work (I've done stuff like this before) it throws off all the movements that aren't straight forward

#

Ok so let's say this:

fickle sapphire
#

Let me give an example

#

Player object's position is 0,0,0. Target position is 10,0,0. Movement vector provided by the animation's root motion is 1,0,0.

#

When the player's rotation is Quaternion.identity, the local axis lines up with the world axis, so no problems here

#

however let's say the player is rotated 90 degrees

#

now the target position will be 0,0,-10 and the movement vector will remain the same

#

For some reason, rotating by the target position - player's current position isn't working

misty glade
#

Sorry had to step away @fresh salmon , but yeah, that was much simpler and worked without having to touch the quats

#

i'll flip the text around later.. have to step out

fresh salmon
#

Nice! Looks great

misty glade
#

Yeah, I like the effect.. will do some mouseover-hex-highlighting and minimum drag distance and stuff, but .. pretty much works like i wanted it to

fickle sapphire
#

if I just rotate it using the player's current rotation, that delivers the desired result, however, the player will not reach the target destination properly (see original video)

#

see on the second dodge, how when I rotate the player at the end, because the target position has already been calculated, the movement vectors go out of sync

#

this is done using movement = transform.rotation * movement;

dusty wigeon
fickle sapphire
#

yes that's the same thing

#

or TransformDirection I thnk

#

basically it converts the movement vector from local space to world space

#

because this is being applied using the character controller's move() method

#

which takes a world space vector

#

now if I use movement = Quaternion.LookRotation(targetPosition - transform.position) * movement;

#

this is the result

#

That happens regardless of including or excluding Y values

#

I am kerfuffled

dusty wigeon
# fickle sapphire
public class Movement : MonoBehaviour
{
    [SerializeField] private Transform target = null;
    [SerializeField] private float speed = 0.0f;

    private void Update()
    {
        float vertical = Input.GetAxisRaw("Vertical");
        float horizontal = Input.GetAxisRaw("Horizontal");

        Vector3 direction = target.position - transform.position;
        direction.y = 0;
        direction.Normalize();

        Quaternion viewDirection = Quaternion.LookRotation(direction);

        Vector3 movement = viewDirection * new Vector3(horizontal, 0, vertical) * Time.deltaTime * speed;

        if (Input.GetKeyDown(KeyCode.Space))
        {
            movement += viewDirection * Vector3.forward;
        }

        transform.position += movement;
    }
}
#

I do not understand why it is not working.

#

From my side, this work.

#

Vector3.forward would be the animation movement.

fickle sapphire
#

the animation movement has horizontal movement as well

#

like the clip I keep showing is the player dodging to the right, which maintains looking forward on the world axis

dusty wigeon
#

forward can be right, left, down

#

Whatever you want.

fickle sapphire
#

yeah ik, idk why it's not working either, I've been working on this since 8 am this morning lol

dusty wigeon
#
public class Movement : MonoBehaviour
{
    [SerializeField] private Transform target = null;
    [SerializeField] private float speed = 0.0f;

    private void Update()
    {
        float vertical = Input.GetAxisRaw("Vertical");
        float horizontal = Input.GetAxisRaw("Horizontal");

        Vector3 direction = target.position - transform.position;
        direction.y = 0;
        direction.Normalize();

        Quaternion viewDirection = Quaternion.LookRotation(direction);

        Vector3 movement = viewDirection * new Vector3(horizontal, 0, vertical) * Time.deltaTime * speed;

        if (Input.GetKeyDown(KeyCode.Space))
        {
            Vector3 animatorMovement = Vector3.right;
            movement += viewDirection * animatorMovement;
        }

        transform.position += movement;
    }
}
dusty wigeon
fickle sapphire
#

ik

dusty wigeon
#

Try it yourself.

#

My code.

#

I took the time to open Unity and Test it. -_-

fickle sapphire
#

I'm working on it rn

fickle sapphire
#
                    direction.y = 0;
                    direction.Normalize();

                    Quaternion viewDirection = Quaternion.LookRotation(direction);

                    movement = viewDirection * movement;```
dusty wigeon
#

Use only my script. Make a new scene if needed

#

Adapted for Root motion. Could not test it though.

public class Movement : MonoBehaviour
{
    [SerializeField] private Transform target = null;
    [SerializeField] private float speed = 0.0f;
    [SerializeField] private Animator animator = null;

    private Vector3 animatorMovement = Vector3.zero;

    private void Update()
    {
        float vertical = Input.GetAxisRaw("Vertical");
        float horizontal = Input.GetAxisRaw("Horizontal");

        Vector3 direction = target.position - transform.position;
        direction.y = 0;
        direction.Normalize();

        Quaternion viewDirection = Quaternion.LookRotation(direction);

        Vector3 movement = viewDirection * new Vector3(horizontal, 0, vertical) * Time.deltaTime * speed;

        movement += viewDirection * animatorMovement;
        animatorMovement = Vector3.zero;

        transform.position += movement;
    }

    private void OnAnimatorMove()
    {
        animatorMovement += animator.deltaPosition;
    }
}
fickle sapphire
dusty wigeon
#

Because it is working on the side too.