#archived-code-advanced

1 messages · Page 53 of 1

lethal vale
#

I'm writing a grid system but I have a mathematic problem with getting the node from a world position. I basically wanna snap to the node as soon as the target is inside the square around the node (the unity grid is representing the square i mean). However as you can see in the video this is not working right now.

public Node NodeFromWorldPoint(Vector3 worldPosition) {
        float percentX = (worldPosition.x + (width / 2f)) / width;
        float percentY = (worldPosition.z + (height / 2f)) / height;
        percentX = Mathf.Clamp01(percentX);
        percentY = Mathf.Clamp01(percentY);

        int x = Mathf.RoundToInt((width - 1) * percentX);
        int y = Mathf.RoundToInt((height - 1) * percentY);

        return nodes[x, y];
}
public void CreateGrid()
    {
        nodes = new Node[width, height];
        
        var name = 0;
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {

                Vector3 startPosition = new Vector3((width) / 2, 0, (height) / 2) - new Vector3(0.5f, 0, 0.5f);
                Vector3 worldPosition = (transform.position - startPosition) + new Vector3(x, 0, y);

                nodes[x, y] = new Node(true, worldPosition, x, y);
                if (visualizeNodes) {
                    nodes[x, y].createInstance(nodeInstance);
                }
                name++;
            }
        }
    }

How would I tackle this issue? What mathematical mistake have I made?

glossy harness
#

Hey guys, so I implemented client side network latency prediction in my game with server authoritative reconciliation. However my camera jitters a little bit when reconciliation happens, Is there some sort of way how I can reduce this camera jitter?

I believe the jitter occurs because the camera script just follows the player object with an offset:
mainCamera.transform.position = new Vector3(transform.position.x + xOffset, yOffset, transform.position.z + zOffset);

and when reconciliation happens there is a bit of jitter depending on how desynced the server was from the clients player (the larger the desync the more jitter)

I'm thinking the jitter on the player object is fine and acceptable, but the jitter on the camera needs to be smoothed as it is extremely jarring to have the entire scene jitter like that.

Any ideas?

latent moss
latent moss
glossy harness
#

The camera follow logic exists in its own script which only runs client side

#

its pretty much just this line: mainCamera.transform.position = new Vector3(transform.position.x + xOffset, yOffset, transform.position.z + zOffset);

#

The rigidbody of the player is being synced over the network, with client prediction in place to keep it responsive

#

its probably my client prediction logic which is causing the jittering

#

Do you think I should use Vector3.SmoothDamp or Vector3.lerp for the camera?

latent moss
static marsh
#

When I run CodeSignAppBundle manually after creating a build, a window with “code signing app” gets stuck open and never closes. Is there a way to fix this? Unity 2021.3.21f1 on Apple Silicon

latent moss
# latent moss You can try my script and if it works for you, you can compare it to yours and m...

The white grid on the bases ground is done via shader, i have attached it for you too.

And this should in be the script / on the object you want to snap to the grid:

Ray ray = PlayerCam.ScreenPointToRay(Mouse.current.position.ReadValue());
RaycastHit hit;
if(Physics.Raycast(ray,out hit)){
    if(hit.transform.tag != "Grid"){return;}
    Vector3 target = hit.point;
    GameObject hitObj = hit.transform.gameObject;
    GridSnap grid = hitObj.GetComponent<GridSnap>();
    Vector3 checkPos = grid.snapGrid(target);
    //Debug.Log(GridSnap.isOnGrid(checkPos));
    if(GridSnap.isOnGrid(checkPos) || GridSnap.allowOutOfBounds){
        transform.position = checkPos;
    }
}```
(using new input system here)
...
static marsh
lethal vale
#

the only issue i have right now is that it just doesnt snap because of a mathematical error and i hope someone could figure it out

latent moss
#

The code i posted is under 70 lines, you could check and see how i done the math there. Also, if the maths in your script is wrong, then imo it should still atleast snap somewhere (off position)

latent moss
lament salmon
#

That's what you are using to highlight the closest node right?

latent moss
latent moss
scarlet plume
#

This probably qualifies as advanced, but I'm not sure.

Is it possible to create a 2D sprite AnimationClip at runtime (I load sprites from StreamingAssets folder). I don't see anything that isn't related to curves in the documentation.

reef void
#

Any experiences coders have any tips to get started learning coding and be able to figure out how to code your own mechanics and stuff on your own?

compact ingot
hushed fable
latent moss
devout coyote
dusty wigeon
scarlet plume
#

I'm not going to create clips on the fly during the gameplay, but only when the game is initializing

prisma wharf
#

Unity UI freezes after calling .ContinueWithOnMainThread (snapshot => .ContinueWithOnMainThread(...)) (simplified)
Unity 2021.3.22, firebase latest version. How to fix it?

#

and when .ContinueWith (snapshot => .ContinueWithOnMainThread(...)) (simplified)

dusty wigeon
dusty wigeon
# prisma wharf Unity UI freezes after calling .ContinueWithOnMainThread (snapshot => .ContinueW...

There is no way someone can just magically help you there. You will need to learn the step of debugging in #💻┃code-beginner or #archived-code-general. Ask for someone to guide you through the process of debugging. (What should I look at ?)

There is multiple question that you need to ask yourself such as:

  • When the error started to occur ?
  • What code/data is the source of the error ?
  • What is the actual error ? (Null exception, Out of bounds, etc.)

Then you can proceed to try and find a solution:

  • Can I edit the code ?
  • Is there any parameters that I wrongly set ?
  • Can I remove the feature ?
prisma wharf
# dusty wigeon There is no way someone can just magically help you there. You will need to lear...

havent I tried like multiple times thinking and fixing it? Even try-catch cant catch any errors with this .ContinueWithOnMainThread which seems just to freeze ONLY Unity Editor's UI, but code itself. After searching for whole days in google I havent found anything that would help me. Doing ContinueWith seems to help UI not to freeze, but there is racing condition or just UnityAPI methods that cant run on non-main thread that are preventing code from executing further. Nothing in Editor.log, nothing in Player.log. Just clear silence..

scarlet plume
#

Are you sure you are even getting the response from Firebase?

prisma wharf
#

1000% sure

dusty wigeon
prisma wharf
prisma wharf
#

Gonna check about Parallel Stack

dusty wigeon
prisma wharf
dusty wigeon
#

Then why is it not working ? There is multiple people that does not have your issue. You must have done something differently then them. What did you do ?

prisma wharf
#

Running auth from Unity Editor? Broken ContinueWithOnMainThread after lambda expression?

dusty wigeon
prisma wharf
#

Like running coroutine (I even used a dispatcher to the main thread for this) and then sending user data back to firebase

#

But my database rules forbid access if userid ≠ database cell name (for security purposes) so I had to do something with unity as it disables me from doing Google play games sign in

dusty wigeon
#

Would it possible that the code inside ContinueWithOnMainThread never end ?
If you remove what is inside the ContinueWithOnMainThread , does it work ?
If you use other means of Synchronisation, does it works ?

If the Editor hang, it is because you have an intensive or never ending code running on the main thread.

This is as far as I go, if you want more help consult #💻┃code-beginner or #archived-code-general and ask people how you can proceed to track down the error and find a solution.

bold berry
#

when i use values for x and z like 1, my level expands one time and then overlaps the other tiles, but if i would use 2 or more i get a corner cutout. https://hatebin.com/owzlcjuzon

dusty wigeon
bold berry
bold berry
#

this now happens when push button e for testing purpose

#

but i want to expand when you go next level

prisma wharf
dusty wigeon
prisma wharf
#

As always - non-main thread

dusty wigeon
# bold berry expand the level in rows and columns by 1

From what I am looking at your issue would be

for (int z = 0; z < zPlatforms; z++)
        {
            for (int x = 0; x < levelWidth; x++)
...

and

for (int x = 0; x < xPlatforms; x++)
        {
            for (int z = 0; z < levelWidth + zPlatforms - 1; z++)

You are iterating on every tiles instead of only the newly created.

dusty wigeon
dusty wigeon
bold berry
#

idk

#

nvm i fixed the issue

dapper cave
#

that's a weird one: JsonUtility.FromJson can serialize a List of Vector3 but deserializing it returns null

dapper cave
#

i'm sure it hit the depth limit ... because no one makes creatures with a depth of >10

#

unity's concept of game stuck with that spinning ball from 2006

#

alright swapping for another serializer

real blaze
#

hi, is there a way to check if a certain assembly exists in the domain, during compilation? (using preprocessors)

dusty wigeon
#

Most of the time, you gonna have something like. Try your best to NOT do this as this is terrible ugly and hard to maintain. The best would be to have an interface such as ISaveManager which then you reimplement for each platform using Assembly Definition.

using UnityEngine...

#if Steam
using Steam;
#endif

#if Steam
public bool UseSteam => true;
#elif
public bool UseSteam => false;
#endif

private void Awake(){
  ...
  #if Steam
  Steam.[...];
  #endif
}
real blaze
#

I really expected C# to have the functionality :(

valid scarab
#

anyone know how to fix dll file showing only PE despite having same size?

hardy sentinel
real blaze
#

context:
am writing a plugin, and this plugin needs to adapt when a specific other plugin is present. so it needs to know if that specific plugin is installed, but the specific plugin offers no define word

hardy sentinel
#

you don't have to change the assembly's code to add define 😄

#

oh

hardy sentinel
#

would look like this: PlayerSettings.SetScriptingDefineSymbolsForGroup(currentBuildGroup, currentDefineSymbols + ";NEW_DEFINE");

#

-- in a OnBeforeBuild script -- or in your custom Build() method

#

hm you can actually check if another assembly is present

real blaze
#

oh I get what you mean. to add a define using editor magic. good idea

#

thanks!

hardy sentinel
#

AppDomain.CurrentDomain.GetAssemblies().Any(x => x.Name == pluginName);

#

yup! and if you do that while building -- it's practically a pre-compilation pass 🙂

sweet stump
#

Hello there, I´m making a game where I generate objects in their spawn positions in a warehouse and then use a forklift truck to move those objects to the delivery trigger. The problem is that the trigger isn't working, the objects aren't being destroyed, the count of objects picked isn't going up and I don't even get the Debug.Log message when I get with the object inside the trigger

#

Both the prefab and the trigger object have the same tag

#

it's the ItemListManager

#

the Item script only has the quantity

#

it generates 8 clones of the prefab each time I start the game

#

each clone goes to a different spawn location

#

anyone might know what the issue is?

#

tell me if you need more info

hardy sentinel
#

how can people work in April Fools lol.. I've been trying whole day.. wrote 2 lines of code

#

.. + another 30 while answering code questions I guess

hardy sentinel
sweet stump
#

well... I have to xd

hardy sentinel
#

why? :/

sweet stump
#

university

hardy sentinel
#

they can't possibly be forcing you to work on a Saturday xD

sweet stump
# hardy sentinel what exactly isn't working?

the trigger collider... the game is generating the prefabs on their places like it should, but when I transport them to the delivery trigger, it just doesn't work and I don't know why

hardy sentinel
#

I don't see the 'ItemListManager' component passing through your objects, or having a collider in this matter.. it makes sense that its trigger events are not called

gaunt mantle
sweet stump
#

the collider is on both objects

#

should there be a collider on the parent?

hardy sentinel
sweet stump
hardy sentinel
#

np. it's best to ask to the appropriate channel because people with the appropriate patience hang out xD
I just usually tab here hoping to just answer in 1 sentence and tab out again

#

in #💻┃code-beginner it's quite common for people to give nice and detailed answers on such questions -- here, not so much

sweet stump
#

okey, thanks anyway

#

and sorry xd

hardy sentinel
#

np 😛 I just gotta go asap, thought I'd mention it at least 😄

sweet stump
#

wait, what you said actually made me have progress on the problem

#

I changed the ItemListManager script to the object that has the collider and now the trigger is giving me the console message

hybrid belfry
#

Hello. I am looking to solve an odd issue with one of my variables becoming null unintentionally. Whenever I change some code in my GridController.cs class, my grid variable becomes null. This is an issue because Sprites are drawn on the grid when the grid is recreated. Grid recreation happens when the grid is null using the OnDrawGizmos() method. I end up with duplicate sprites because the grid is for some reason null, although the inspector says otherwise. Does anyone know why this happens? Thanks

#

Here is shot of the editor - As you can see, I should have 9 sprites, but have double, and the debug line printed true :/

brisk otter
#

Got a problem and have exhausted all options, really just need to know if this is a unity bug before I spent time trying to fix. I am using a tilemap in a 3d World that has its swizzle set to XYZ so that the issue is that when using the tilemap extras package the gameobjects created by rule tiles do not respect the swizzle and are rotated incorrectly ( See image). Is it possible to edit the default RuleTile script and change this behaviour? I have never edited unity scripts directly. Any other solutions and suggestions are greatly appreciated!

hybrid belfry
plain granite
#

you could try adding the [Serializable] attribute to your Cell class

hybrid belfry
#

I tried that but it didn't help. I previously tried that and also using [SerializeField, HideInInspector] but didn't change anything

dusty wigeon
young nexus
#

How can I implement global hotkeys in Unity [C#]? I'm working on an overlay and I want to be able to call methods when I hit specific keys when my Unity application is not in focus. Does anyone know of a good working implementation for them?

dusty wigeon
# young nexus How can I implement global hotkeys in Unity [C#]? I'm working on an overlay and ...

You will need to dive in "System Hooks". I do not know if there is any library that can help you there. Know that this procedure will be platform dependent, meaning that you will need to find the solution for each platform you deploy on.

Here a list of articles that could guide you in a Windows implementation.
https://www.codeproject.com/Articles/802412/Global-Interceptable-Program-and-System-Hooks-in-N
https://learn.microsoft.com/en-us/archive/msdn-magazine/2002/october/cutting-edge-windows-hooks-in-the-net-framework
https://learn.microsoft.com/en-us/windows/win32/winmsg/using-hooks

sly shore
#

Hey, (I have no idea if this is advanced or general, i'm sorry if this is the wrong place) I'm working on a game with a lot of stats for the player (like health, resistances, attackspeed and stuff). I also need to manipulate these stats through items, gear, crafting etc and I dont want to add all of the stats over and over to all other scripts.

So I decided to create a stat script with a class for creating a new stat (Screenshot 1). Ignore the Tiers and Rolls, just about the name and the value for now.

Then I declare all the stats so I can configure them in the inspector (Screenshot 2).

In the next step i create a bunch of lists for the stats and add the new stats via the class to the lists, with the values from the inspector (Screenshot 3). Now when I create a new script for items I can just copy the list with the stats from the stat script and my item script has all of the needed stats. Also if I add some new stats in the stat script I dont have manually add all of the new stats to all the other scripts.

So far so good, everything is working. The downside of that is that I can only call the stats by "commonStats[x].value" so I need to check the order of the stats all the time because I cant just call a name... And that is very time consuming and also terrible for readability.. So my question is: Is this the right way to do something like that or is this totally garbage and there is a way better solution? Or is there a way to access the stats in another way by calling them by their names? Help is much appreciated!

gaunt mantle
#

linq?

gaunt mantle
#

and you can get a group of stats by other params like ```cs
var coldResistances = resistanceStats.Where(o=>o.statValue == coldResistance).ToList();

compact ingot
sly shore
sly shore
gaunt mantle
#

can query by any of the properties, you can get all items with a minRoll of 3 for example, or by ID if you add ids

sly shore
#

I'm also willing to scrap the whole code if there is a better solution.. just want to get it right before the system is too deep integrated

dusty wigeon
# sly shore yes, i want to show the names and values in the UI, items and stuff

You should use ScriptableObject to hold each stats Identity instead of name.

public class StatDefinition : ScriptableObject 
{
  public enum Type 
  {
    Offensive,
    ...
  }

  [SerializeField] private string name;
  [SerializeField] private string description;
  [SerializeField] private Image icon;
  
  [SerializeField] private Type type;
  ...

  public Stat Instantiate() { ... }
}
regal olive
#

Running into a dilemma implementing the State Machine pattern. I have to decide whether to represent State either as an abstract class

abstract class State {
    enter(context: StateMachine): void { console.log('some default message') }
    abstract execute(context: StateMachine): void
    exit(context: StateMachine): void { console.log('some default message') }
}

or as an interface

interface State {
    enter(context: StateMachine): void
    execute(context: StateMachine): void
    exit(context: StateMachine): void
}

The advantage of going with the abstract class is that I'm able to give .enter() and .exit() default behavior that's auto-inherited and only needs to be manually implemented by subclasses if they wish to override behavior. The only thing necessary to always implement is execute()

The disadvantage is that all subclasses will need to invoke the super() constructor, which feels pointless given that State has no fields to be constructed - its a class with only methods.

class IdleState extends State {
    duration: number

    constructor(duration: number = 30) {
        super() // <-- feels pointless
        this.duration = duration
    }

    execute(context: Character): void {
        console.log('some execution logic')
    }
    // enter() and exit() inherit default behavior
}

I avoid having to super() in every sub-class if I go with an interface, but I run into a similar frustration: every implementer class will have to manually implement enter() and exit() , even if no behavior is needed in that particular state.

class IdleState implements State {
    duration: number

    constructor(duration: number = 30) {
        this.duration = duration
    }

    execute(context: Character): void {
        console.log('some execution logic')
    }
    // I have to manually implement these even if no behavior is needed
    enter(context: Character): void { }
    exit(context: Character): void { }
}```
compact ingot
regal olive
#

just functions to be ran during .execute etc. ?

compact ingot
#

something like this

new GenericState(key: State.Foo, onEnter: () => {}, onExit: default));
#

or make a builder pattern to configure it without ever instantiating a state class

regal olive
#

what would some of the methods be?

compact ingot
sly shore
regal olive
regal olive
#

what if functions get quite involved

#

like lots of lines

#

where do I store, or how do I represent that?

compact ingot
#

or inject a method on a different class altogether

regal olive
#

where would I put that method?

compact ingot
#

wherever you like

regal olive
#

like, the inheritance approach is nice and organized

#

the execute logic for Idle is in Idle

#

with the injection method, i dunno where I'd store that

compact ingot
#

the point is that this pattern separates execution of the FSM entirely from the states' implementation and allows you to implement it all as concisely in-place or as elaborately in whole other classes/modules as needed

#

nobody wants to use inheritance to use your FSM (not even you yourself down the road)

#

so make it an interface and/or use injection

haughty shell
#

Wanted to ask about modular AI movement system.
I have behaviour where enemy moves towards the player.
I also have behaviour where enemy moves towards the player only to some distance, and then maintain this distance.
Also behaviour where enemy dashes on some condition.
I want a flexible approach to compose AI movement. I need some way to create variations like [towardsPlayer + Dash] enemy, [towardsPlayer + maintainDistance + Dash] enemy, [randomDirection + Dash].
My first Idea was to create movement decorators with ScriptableObjects, but there is some problems with this approach. For example, towardsPlayer triggers on collisions to check if its "arrived", so if I want to wrap it, I will need to redefine onCollision triggers in the whole wrap link (and pass them to collision triggers in the movementController).
Also I have some problems with passing dependencies. Components such as rigidBody and enemyTransform should be public to define them in Start() of movementController which doesn't seem a right way to do.
Is there are ways to solve thess problems, or maybe some completely different approaches?

dusty wigeon
dusty wigeon
# regal olive Running into a dilemma implementing the State Machine pattern. I have to decide ...

In TypeScript, I think you do not need to call super() if you do not have a construct for your parent class. Having used multiple interfaces of StateMachine, I must say that I prefer to have to define function same if there are not necessary. It feels more homogenous and it is easier to understand. It all comes down to your preference and what is your style.

At the moment, I rollup with Template Method pattern paired with StateMachine. I make my State class abstract and implements the function InternalEnter/InternalExit. It helps in giving the ability to add observer to the Enter and Exit function.

public abstract class State {
  public event System.Action OnEnter;
  
  public void Enter() {
    OnEnter?.Invoke();
    InternalEnter();
  }
  private abstract void InternalEnter();

  ...
}
sly shore
dusty wigeon
thorn flintBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

haughty shell
#

Thanks 👍

regal olive
#

Once I have a procedural planet generator how would I take that and implement it into my unity game? Like I want a bunch of places. Like sea of thieves, but planets. Then I can explore them.

dusty wigeon
#

This can be complicated for beginner or intermediate programmer as it requires a specific knowledge to make everything works fluidly. (Reasonable FPS)

regal olive
#

Yeah

#

What can I start with tho

#

Like can i procedurally generate a planet and then put it into my assets

#

To use it as a mesh

regal olive
#

So it’s not creating a planet every time I press play

#

Like

dusty wigeon
#

You will need to create a structure that support LOD likes what Unity Terrain does.

regal olive
#

The coding adventure by Sebastian lauge

#

It is a very good example of what I’m trying to do

#

But I don’t quite understand it

dusty wigeon
regal olive
#

Yeah

#

IR

#

OR

#

IS THERE A SIMPLE PLANET MAKING STRATEGY IN BLENDER

dusty wigeon
regal olive
#

I know that

#

Like forget about the procedural generated

#

If I can manually make each planet in blender

#

Tedious but it would be more personalized to my fantasy game

#

Ya know?

dusty wigeon
#

It can be a valid approach. It would definitely be more easy to implements if you have talent (or aspiration) in 3D modeling.

regal olive
#

Yeah

#

I have been making a blender planet

#

But

#

What I’ve been trying to do is getting a water shader

#

I’ve downloaded a ton of water shaders but they don’t work

dusty wigeon
#

Know that, for large object, you will need to make a structure that support LOD and you won't be able to produce this from Blender.

regal olive
#

Wdym

#

Don’t understand what u just said

dusty wigeon
#

There is a limit on how much triangles a computer can render at a time. If your planet is 100'000'000 triangles, you will never be able to render it completly.

regal olive
#

The planets won’t be that big

#

Not like no man’s sky

#

Way smaller

#

Would the water shader in that video work on an i ops here?

dusty wigeon
#

If this the case, then you might be fine. But usually, for terrain, it gets big really fast.

regal olive
#

Icosphere*

dusty wigeon
#

So, I am afraid not.

regal olive
#

So how could I make one that would work

#

And should I use the 2021 or 2022 version

#

For unity

dusty wigeon
#

I am not an expert in Computer Graphics. I do not know how you could proceed.

regal olive
#

I am using 2022

#

Should I use a different version

#

Or am I okay

dusty wigeon
regal olive
#

Alr

dusty wigeon
regal olive
#

It’s not inside an icoshpere

#

It is the icosphere

#

Like instead of a water shader for a plane, it’s for a sphere

dusty wigeon
#

Inside, like fulling the whole body.

#

This is what I meant.

regal olive
#

No

#

Not like filling it

#

You know how the shaders are like a texture

#

And u just drag it onto a plane and now u have water

dusty wigeon
#

Textures are components of a shader.

regal olive
#

Okay

#

But u do drag the shader onto the plane to get water tho right?

regal olive
#

So can I drag the shader onto an icosphere

#

Or will that not work

dusty wigeon
#

If the shader has been made correctly for the use case your doing.

regal olive
#

So I have to make my own

dusty wigeon
#

I mean, you can try to see how it looks, but I am pretty sure it is going to be ugly as hell.

regal olive
#

Hmm

dusty wigeon
regal olive
#

Dammit

#

Hmm

#

Okay

#

What about a space ship

#

How could I make a spaceship that is good

#

Not like the unity plane

#

I hate it

dusty wigeon
#

I am not sure what you mean. You will need to either purchase one or create one.

regal olive
#

I’m gonna create one

#

But controlling it is the thing I want

dusty wigeon
#

There is also an abundance of tutorial on how to do one.

regal olive
#

Okay

steel snow
#

how do you add a list to a native list in unity

#

their copy from method only supports native collections

scenic forge
steel snow
#

no just convert a list to native list but i figured it out

scenic forge
#

Yeah you can just allocate and copy the content over.

steel snow
#

yeh turns out i cant write to a native list in a job anyway

#

so that was a total waste of time 😄

scenic forge
#

Wdym? You can.

steel snow
#

it says it doesnt support parallel writing

#

im using parallel for job

scenic forge
#

Yeah parallel job is different from a regular job, it's to prevent race conditions.

steel snow
#

what race condition happens with adding to a list ?

scenic forge
#

You can use a queue instead.

steel snow
#

wouldn't a queue also have the same issues

scenic forge
steel snow
#

yeh but i dont need the the list in a particular order

scenic forge
#

And also resizing issues.

steel snow
#

ah i see

#

wouldnt that same issue happen with queue then

scenic forge
#

As well as moving the head of the list.

#

Queue IIRC is implemented to have a buffer for every thread, so each thread is only writing to its own buffer

#

And at the end you dequeue all items in one single thread.

steel snow
#

why wouldnt that just add that support to a list

#

like a concurrent list

scenic forge
#

🤷‍♂️

#

From an API design perspective, it's not unreasonable to say that "lists don't support parallel writing because we anticipate vast majority of the use cases to not be parallel, so they don't need to pay the price"

#

Optimizing for the majority, basically.

steel snow
#

that seems odd theres lots of parallel jobs you can do with lists

scenic forge
#

I think the biggest thing is that similar to the dequeue process of queues, the reconciliation of states of each thread must happen in one thread, which will have a different API surface.

#

Either way yeah if you just want to append in parallel, queue is the way to go.

steel snow
#

@scenic forgedo you know how to copy one native list contents to another in main thread ?

#

i tried buffer.CopyFrom(output) but i think that iterates the elements rather than replaces

hardy sentinel
#

job data --> main thread shouldn't happen while the job is running -- if that's what you're saying :p

steel snow
#

huh ?

hardy sentinel
#

typically you just assign to a new var to copy afaik:

void OnUpdate(..) {
  if (cachedResults.IsCreated) { cachedResults.Dispose(); }
  cachedResults = latestResults;
}
steel snow
#

cant you have to dispose of native collections

#

so the reference is lost

scenic forge
#

Do you really need to copy though, can you pass that directly to whatever needs it?

hardy sentinel
#

hm yeah I think that's what I do unwillingly then 😄

scenic forge
#

If you really need to copy, you can just do the dumb way of looping over and copying; or you can resize uninitialized and mem copy the underlying buffer over, probably a bit faster.

steel snow
#

i copy because i cant remove in parallel

#

but i might try a new approach

scenic forge
#

Potentially an XY problem, what's the bigger picture?

steel snow
#

i create a new buffer of triangles that do not belong in another

hardy sentinel
#
  • mind u can dispose whenever you want in a certain timespan (or even no timespan if you don't specify Alloc.Temp)
    Create & Forget is a pretty powerful possibility when using DOTS & native arrays -- in the cost of some memory if u can afford it
    (I'm probably useless here but really bored so gonna say my input either way xD)
steel snow
#

then i copy that to my original triangle buffer as the new buffer

scenic forge
#

No like the bigger picture

#

Are you trying to generate triangles in multiple threads then combine the results?

steel snow
#

yeah

scenic forge
#

What about queue?

steel snow
#

well i found out list cant write in parallel

#

so i didnt need queue

#

im not sure why its not working vs my main thread algorithm atm

#

its hard to debug

scenic forge
#

Each thread writes to the queue, then once everything is done, main thread dequeues into the list as the combining step.

steel snow
#

oh i think i see the error

#

hmm its slower than my damn main thread algorithm

#

makes no sense

scenic forge
#

Parallel algorithms are typically bottlenecked by the final combining step which aggregates the results from all threads

steel snow
#

what does that mean exactly

#

is it the parallel writing thats eating the cost

#

i get roughly 10 to 15 fps less using jobs vs all main thread

#

crazy

scenic forge
#

Well in that case there's probably issues with your algorithm.

steel snow
#

its the same algo but i put the steps in parallel fors

#

i checked the profiler the jobs are running

#

no burst though but not much math going on in the first place

scenic forge
#

Are you allocating for each job?

steel snow
#

yeah im creating native lists for my outputs

#

example:

                // remove all bad triangles from tris
                var newTris = new NativeList<Triangle>(tris.Length, Allocator.TempJob);
                var job3 = new RemoveBadTriangles(badTris,tris, newTris.AsParallelWriter());
                job3.Schedule(tris.Length,4).Complete();
                tris.CopyFrom(newTris);
                newTris.Dispose();
                badTris.Dispose();
                ////////////////////
scenic forge
#

And you have to combine those lists to yield a final output.

steel snow
#

no i use 2 buffers and copy it

#

so i have input, comparer list and output list

scenic forge
#

I don't think I can give much advice without you telling exactly the problem you are solving, I suspect there are better ways to parallelize.

steel snow
#

the problem is the low frame rate

#

it works but it slow

#

i can't identify the cause of the slowness

scenic forge
#

No, I'm asking what the problem you are solving with this algorithm.

steel snow
#

its deluanay triangulation

#

most of the jobs involve comparing two lists and populating a new one

#

which is the only thing that can realistically be done in parallel

scenic forge
#

Hmm, not familiar with that specific problem then, you might look around and see if there are parallelized algorithm for it.

steel snow
#

i am using the parallel approach

#

it works but its slow which is more an issue with jobs than the algorithm

hardy sentinel
#

.Complete() should be what causing the framerate issues. You can control your jobs flow better

scenic forge
#

The thing about parallelizing algorithm is that, the things you parallelize will speed up a factor of CPU cores, however you are also paying a fix cost of spinning up threads + allocations for each thread + combining results from all threads.

hardy sentinel
#

like: Schedule the jobs, and once they're all ready, have them render. Then restart the jobs

steel snow
hardy sentinel
#

schedule the next job with those as dependencies, then?

steel snow
#

you can see here a whole 50fps lost almost

scenic forge
#

Have you profiled it and see what's taking majority of the time?

steel snow
#

complete is the main one it seems

hardy sentinel
#

well u likely should decouple it from MonoBehaviour as well

steel snow
#

thats the caller for the start of the job

hardy sentinel
#

just standalone rendering system from which a MonoBehaviour gets its data by accessing cachedResults

steel snow
#

what is that code you posted 🤔

#

not seen anything about that in job system

#

oh entities im not using

hardy sentinel
#

oh.

steel snow
#

this is just jobs with regular data

hardy sentinel
#

well.. use entities 😛

steel snow
#

no need the algo is just raw data anyway

#

the monobehaviour just calls the job

hardy sentinel
#

jobs are just part of DOTS, not sure if intended to be used in a standalone manner

scenic forge
#

You can use it standalone.

steel snow
#

yeh but im not using gameobjects its just mesh data

#

the visual is just shader output to see it

#

all the data is data orientated anyway

#

so entities wont add much other than more boiler plate

hardy sentinel
#

it would add a background worker that schedules and waits for the threads, then syncs to main thread 😛

#

which is.. all one would ever need to ensure high FPS

steel snow
#

im pretty sure jobs is already in the background without entities

scenic forge
#

What's inside each job?

hardy sentinel
#

but in this case you schedule and Complete them in main thread, in the span of a single frame

steel snow
#

theres a fair few but they all do element compares and populate new lists

hardy sentinel
#

but I guess you're right. TLDR as long as you can do without Complete, it'll be fine no matter where you schedule them from

steel snow
#

this is probably the most complicated job:

       [BurstCompatible]
        public void Execute(int index)
        {
            Triangle tri = _badTris[index];
            for (int e = 0; e < 3; e++)
            {
                Edge edge = tri[e];
                bool rejected = false;
                for (int k = 0; k < _badTris.Length; k++)
                {
                    if (k != index && _badTris[k].HasEdge(edge))
                    {
                        rejected = true;
                        break;
                    }
                }
                if (!rejected)
                    _edges.AddNoResize(edge);
            }
        }
#

but even thats not too complex

scenic forge
#

If majority of the time is spent on .Complete() then it must be the job itself.

steel snow
#

the job is the same code as my main thread though

#

but its parallelfor

#

so it should be faster

scenic forge
#

If instead of .Schedule(...) you do .Run(...) that will make the parallel job execute the same as a simple for loop on the main thread, and if that's still slower, then there's something fishy going on.

steel snow
#

oh good idea

scenic forge
#

If it's still magnitudes slower, then surely your code isn't the same and differs subtly in some way.

steel snow
#

in Complete() the wait for JobGroupID is the one that takes longest

#

8 times more than my own functions

#

hmm ok its 50% slower using Run()

#

thats a concern

stiff hornet
#

opposite actually

#

means it is parallel and quicker

steel snow
#

huh?

stiff hornet
#

the issue is that you are completing straight after the schedule

stiff hornet
scenic forge
#

Well it's both good that parallel is indeed faster so the parallelization is working, but it's also bad that it's still slower than a plain version without Job system.

stiff hornet
#

and you've just said Run is slower, which is what you want

steel snow
#

i know burrito sugguested to try Run to see if its still slower than my main thread version

#

my run version is slower than my original main thread version

#

which is weird

stiff hornet
#

well there is still a cost to use the job system

#

even if it is just Run()

#

which i guess is a bit weird

scenic forge
#

Surely the cost isn't that big enough to drop from 50+ FPS to 10.

steel snow
#

exactly

stiff hornet
#

fyi you are not bursting it

steel snow
#

the whole parallel version is 50% slower than my main thread approach

stiff hornet
#

[BurstCompatible] is not correct

scenic forge
#

Their other version isn't Bursted either, I assume?

stiff hornet
#

you want [BurstCompile], on the job struct too

#

non bursted jobs are a lot slower

steel snow
#

but still threaded so why do i get a drop in frame rate

#

it should not be that much slower than having it all main thread thats crazy

scenic forge
#

Are both versions non Bursted?

steel snow
#

right now i have it all using Run and thats also slower than the main thread one

#

i lose 50 frames ish

#

so they both main thread yet slower

stiff hornet
#

try to burst it

scenic forge
#

Is your main thread one also non Bursted?

steel snow
#

ok though there isnt any math going on really its all list comparisons

stiff hornet
#

the profiler will show green bars when bursted for the jobs

scenic forge
#

Well Burst does more than just improving math operations, the code gen is very good

#

But that's really besides the point, if the same code written in a plain for loop, taken to a plain Job running on main thread, is suddenly magnitudes slower, then there's something else going on.

steel snow
#

exactly

#

this is the Run() profiler

#

i actually get more info when its main thread which is nice

steel snow
#

its pretty bursty still slower than main thread 😄

#

they aint even slow

#

so i dunno why its causing such a slow down

scenic forge
#

If you can post the implementations of both versions, people might be able to spot the issues.

steel snow
#

ill have to do that when i get home thats a lot of code

#

wont have time atm

stiff hornet
#

it looks like your jobs are too quick

steel snow
#

too quick?

#

how is that a thing

stiff hornet
#

on the ParallelForSchedule you can tweak the loop count

steel snow
#

yeh i put 4

stiff hornet
#

try higher

steel snow
#

oh is it likely making too many threads due to low count

#

hurting my perf

stiff hornet
#

yeah thats what i'm thinking (more so the cost of scheduling it all than threads but yeah)

scenic forge
#

Aren't you doing the .Run()?

steel snow
#

no im back to burst

scenic forge
#

(And still getting slower result)

steel snow
#

how do i choose good batch size

scenic forge
#

Pretty much trial and error

steel snow
#

ok that made a huge difference

scenic forge
#

But I wouldn't bother with that until I figure out what's going on that .Run() is slower than your main thread version, from my experience that shouldn't happen.

steel snow
#

thats a good point

#

ill do some debugging later tonight using Run to see whats up there

manic shoal
#

hello all... how can i check if 2 fields are equal??
I would like to ensure that when the user chooses a password he must also confirm it ... in this case I make the button interactive
I tried like this but I can't also because thinking about it, the 2 variables for the password are always emptyif I don't confirm them first...

if (confirmPassword == password)
{
ConfirmRegButton.interactable = true;

         ConfirmRegButton.onClick.AddListener(() =>
         {
             StartCoroutine(Main.Instance.Web.RegisterUser(UsernameRegInput.text, PasswordRegInput.text));
         });
     }
manic shoal
hardy sentinel
#

can code-advanced in 2 month use unity

manic shoal
#

sure not... but in other section no answer me..

#

and i try whit expert people...

regal olive
#

Hi, Im trying to Link Scripts between Folders , someone wanan help?

manic shoal
#

is a registration user....

upbeat path
manic shoal
#

I solved it thanks I was given the entire code to be updated... which many programmers are totally against... well you must know that to teach something the only way is to pass all the code as well because to teach you also need to give examples otherwise someone who is totally fasting if he doesn't have a visual example how can he solve it by reading the normal documentation which, even if he uses examples, are sometimes so generic that he can't solve it??
I'm not arguing and just a point of view and thanks for the support

regal olive
#

Hi

#

Im trying to add Test but when adding a Test Assembly in "Scripts" folder I get an error in one file , saying it cannot find an outside script inside folder "Utils"

Edit: Utils are like packages. But locally ones. Here a screen shot of Battle Transitions in Utils.

upbeat path
regal olive
#

.dll?

upbeat path
#

the file extension of the scripts object

regal olive
#

of its a assembly def (.asmdef)

#

The error happens when the asmdef file is added.

#

if I remove it, the error goes away.

#

and all works again fine.

#

I'm not sure how the Utils folder are connected to Scripts - it seems by magic.

stiff hornet
#

I'd just put the Asmdef in the Assets folder

#

since you are only doing this to get the tests folder working

#

either that or you make a new asmdef for the utils and reference it in the other

regal olive
#

oh, l

#

I have things more correlated to project files in "_project" folder, should i setup there instead?

regal olive
#

I added asmdef in "assets" folder and have this issue.

stiff hornet
# regal olive

so in the tests asdmef did you reference the assets asmdef?

regal olive
#

yeah the issue is. Tests folder seems to require an asmdef file

#

and it used to link "Scripts" and "Tests/EditMode" folder togather. But then I have one .cs file in Scripts that is connected to "Utils" root folder. that's when things go back.

stiff hornet
#

ok, well remake the test asmdef and reference the assets asmdef in it

regal olive
#

There's some glitch I think too. Now I removed all asmdef files but it seems the connected between "utils" folder is wrong. When I press "Play" I runs all scripts in Utils folder as once.

#

nevermind it was a invisible reference caught in git

#

I think the issue is the connection to "utils" folder.

I tried to make each utils folder package (there's 4) with each of their own asmdef file.

The game starts - but the same issue happens as when adding an asmdef in Assets folder.

#

With Assets "asm def file" - screenshot.

#

Without Assets "asmdef"

stiff hornet
#

no console errors?

regal olive
#

The difference is - it adds the "Battle" part and inactivate "SceneContainer" in "Hirarchy" (top part) + Also adds "Save System Setup" in Overworld.

  • Looks like it runs all things in Utils folder as once.
#

I don't get that. that's the bug i guess 🙂

#

@stiff hornet LOts of consoel errors with Assets asmdef

#

none without it

#

its old code from 2019 so... i was expecting some issue nonetheless : )

stiff hornet
#

not too sure why its doing that. Did you try restarting Unity? Might be some weird cache thing not clearing when adding the asmdef

regal olive
#

i can try

#

same issue

stiff hornet
#

can you screenshot the assets asmdef

regal olive
#

Sure

#

i can pritn screen the utils folders too

#

Also all code is available at github

#

If I know how to use Utils with asmdef added, i think that be a solution

stiff hornet
#

are you using an Unity packages as they need to be assigned in the references for that asmdef

regal olive
#

yes

#

there's packages

stiff hornet
#

yeah, just try to add them into the reference list

regal olive
#

oh

#

everyone ?

stiff hornet
#

it's just a bit weird since you should have compile errors

regal olive
#

I think um,

#

my theory is. when no asmdef file exist in "Assets" Unity somehow auto-fixes the references?

#

yeah instead of compile errors, it seems to give NullRefExceptions

hardy sentinel
regal olive
#

Sure,

#

but i still want testable code somehow 😄

#

so that's the bug

hardy sentinel
#

alright.. create Assets/Tests/Tests.asmdef

regal olive
#

Sure

hardy sentinel
#

now add the test script in Assets/Tests folder

regal olive
hardy sentinel
#

and try to run the test. Do you get any errors?

regal olive
#

I can create a test but it would be a PlayMode test, should it be an EditMode ?

hardy sentinel
#

depends.. do you want a playmode or editmode test?

#

just make an edit mode to start with, doesn't really matter

regal olive
#

mm

#

is that alright?

hardy sentinel
#

no.. why is there a new folder and a new assembly?

#

just create a test script

regal olive
#

oh the assembly is added when you use "Create-Tests"...

hardy sentinel
#

this is how u typically create your 'Tests' folder

#

so you can delete your tests folder and 'create a tests assembly folder' and name it 'Tests'

#

or you can just add a tests script

regal olive
#

in root folder?

hardy sentinel
#

just gotta click the 'Create Test Script' button

#

in the folder the tests assembly is on

regal olive
#

Mmh i was followign this tutorial

#

And he create a folder "tests" then two folder inside there "editMode" and "playMode" for different type of tests.

hardy sentinel
#

seems u got everything covered then 🙂

regal olive
#

except i get errors.

#

so i have assets/tests/editmode/editmode.asmdef

#

running without issue. so that's one thing.

#

So i've a test theat runs fine.

#

Now to link it to Scripts. And according to video you add a asmdef inside Scripts folder too

#

and that's when things get fuzzy

#

Cause I've project utils packages. that are hard to understand

hardy sentinel
#

ignore that part, no need

#

just don't create any more asmdef files and you'll be fine (delete the scripts.asmdef also)

regal olive
#

But..

#

how to link Scripts to Tests folder?

hardy sentinel
#

it's linked already

regal olive
#

to test parts of scripts in test folder?

#

ok . the video is from 2020 so i guess things can be different

#

So in editMode i want to test a part from "CustomInputManager" - So i write CustomInputManagerTest.cs and the code is.

#

code of CustomInputManager

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

public class CustomInputManager : MonoBehaviour
{

    public static CustomInputManager cim;

    public KeyCode up { get; set; }
    public KeyCode down { get; set; }
    public KeyCode left { get; set; }
    public KeyCode right { get; set; }
    public KeyCode back { get; set; }
    public KeyCode select { get; set; }

    // Start is called before the first frame update
    void Awake()
    {
        if(cim == null)
        {
            DontDestroyOnLoad(gameObject);
            cim = this;
        }
        else if(cim != this)
        {
            Destroy(gameObject);
        }

        up = (KeyCode)System.Enum.Parse(typeof(KeyCode), PlayerPrefs.GetString("upkey", "W"));
        down = (KeyCode)System.Enum.Parse(typeof(KeyCode), PlayerPrefs.GetString("downkey", "S"));
        left = (KeyCode)System.Enum.Parse(typeof(KeyCode), PlayerPrefs.GetString("leftkey", "A"));
        right = (KeyCode)System.Enum.Parse(typeof(KeyCode), PlayerPrefs.GetString("rightkey", "D"));
        back = (KeyCode)System.Enum.Parse(typeof(KeyCode), PlayerPrefs.GetString("backkey", "O"));
        select = (KeyCode)System.Enum.Parse(typeof(KeyCode), PlayerPrefs.GetString("selectkey", "P"));
    }

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

the test code is

using UnityEngine;
using NUnit.Framework;

public class CustomInputManagerTests
{
    [Test]
    public void TestKeycodeAssignment()
    {
        PlayerPrefs.SetString("upkey", "W");
        PlayerPrefs.SetString("downkey", "S");
        PlayerPrefs.SetString("leftkey", "A");
        PlayerPrefs.SetString("rightkey", "D");
        PlayerPrefs.SetString("backkey", "O");
        PlayerPrefs.SetString("selectkey", "P");

        CustomInputManager cim = new CustomInputManager();

        Assert.AreEqual(KeyCode.W, cim.up);
        Assert.AreEqual(KeyCode.S, cim.down);
        Assert.AreEqual(KeyCode.A, cim.left);
        Assert.AreEqual(KeyCode.D, cim.right);
        Assert.AreEqual(KeyCode.O, cim.back);
        Assert.AreEqual(KeyCode.P, cim.select);
    }
}

#

then this error happen.

hardy sentinel
#

cool

#

add Scripts.asmdef in Scripts assembly

regal olive
#

video screenshot of tests working in unity

hardy sentinel
#

then click EditMode, and reference the Scripts assembly, then click Save

regal olive
#

Added "Scripts"

#

"add the `Scripts assembly, then click Save"

#

now i get this error

hardy sentinel
#

cool

regal olive
#

looking at that script code

hardy sentinel
#

now select the Scripts assembly, and reference the Plugin's assembly

regal olive
#

oh

#

um, there's no assembly in the "utils" packages.

#

but i can make one?

hardy sentinel
#

pretty sure there is one

#

search for the ScreenTransition file, and select the script

#

check which DLL it belongs to

regal olive
#

that is a file inside "Utils" folder- then "Battle Transitions" - "ScreenTransition.cs"

hardy sentinel
regal olive
#

it use [ExecuteInEditMode]

#

so i guess (really new to unity) its a local package

hardy sentinel
#

can you show how this looks on Scripts.asmdef?

regal olive
#

sure

hardy sentinel
#

so both Scripts and Utils are your own code?

regal olive
#

Its user written code yes. I just cloned the repo like a day ago.

hardy sentinel
#

you should instead use _Project.asmdef and the move Utils folder in _Project

regal olive
#

the project is 8 years old

hardy sentinel
#

-- instead of Script.asmdef

regal olive
#

ok

#

but that breaks everything - so i need to make some changes then i assume?

hardy sentinel
#

just gotta delete script.asmdef and instead reference the project.asmdef in tests.asmdef

regal olive
#

ok, sure. i guess i also can add an asmdef into each folder in utils . but.. the issue will be that i think ALL utils code are used at once.

#

the scrrenshots before happen

#

we are back here again.

regal olive
#

wait...

#

ahh, the tests ref works fine now , but the app is buggy : (

#

but yes, the tests seems to work fine.

#

ref to _Project

#

_project

#

now this fffn utils folder is just the issue, tests is added correctly.

#

it seems everything runs at once. so i don't understand why that is. but if i solved that issue, that should be solution

hardy sentinel
#

Cool

regal olive
#

yeah, thanks 🙂

#

its just the utils folder messing it all up, adding test worked fine . x.: )

#

thanks 1 solved, just utils left. 🙂

alpine sinew
#

This was originally posted in #archived-code-general but I immediately deleted and moved here. Hope that's okay.
I have two enums, and a private Method to convert from one to another:

    private enum Vehicle { Plane, Train, None }
    private enum Terrain { Air, Ground, None }

    private Terrain VehicleToTerrain(Vehicle _vehicle)
    {
        switch(_vehicle)
        {
            case Vehicle.Plane:
                return Terrain.Air;
            case Vehicle.Train:
                return Terrain.Ground;
            default:
                return Terrain.None;
        }
    }

Is there any way to prevent Casting outside of this specific Method? I.E. can I prevent casting like this :

Terrain t = (Terrain)Vehicle.Plane;

Or, even worse, this :

Vehicle v = (Terrain)Vehicle.Plane;
stiff hornet
alpine sinew
dusty wigeon
cerulean aspen
#

Hello! I am trying to do a magic system for my game, but in a modular way, with different properties in hierarchies, such as casting type, if its AoE, Projectile, Etc, If projectile, then is it shot or arc, so on. I been trying to figure for days on how to go about on this but so far nothing. I tried an If, Else, return chain, switch case, but it seems too convoluted. Ive also tried scriptable objects, but scriptable objects wont show their own properties on the hierarchy, which is what im looking for. There are some settings that only should be shown to certain "parent setting", but thats also has had me stuck.
What would be a more practical way to go with this?
Thanks in Advance!

alpine sinew
cerulean aspen
alpine sinew
#

you can always check out XML hierarchies:

<spells>
  <spell>
    <name>Fireball</name>
    <type>Fire</type>
    <mana>10</mana>
    <description>A ball of fire that deals damage to enemies.</description>
    <effects>
      <effect>
        <type>Damage</type>
        <amount>50</amount>
        <target>Enemy</target>
      </effect>
    </effects>
  </spell>
  <spell>
    <name>Ice Storm</name>
    <type>Ice</type>
    <mana>15</mana>
    <description>Creates a storm of ice that damages enemies and slows their movement.</description>
    <effects>
      <effect>
        <type>Damage</type>
        <amount>30</amount>
        <target>Enemy</target>
      </effect>
      <effect>
        <type>Slow</type>
        <amount>50%</amount>
        <duration>5</duration>
        <target>Enemy</target>
      </effect>
    </effects>
  </spell>
  <spell>
    <name>Heal</name>
    <type>Restoration</type>
    <mana>20</mana>
    <description>Restores health to the target.</description>
    <effects>
      <effect>
        <type>Heal</type>
        <amount>50</amount>
        <target>Ally</target>
      </effect>
    </effects>
  </spell>
</spells>
cerulean aspen
dusty wigeon
cerulean aspen
dusty wigeon
dusty wigeon
hardy sentinel
#

and it gets 100x better with Odin Inspector with which you can select from abstract types in the inspector:

public abstract class Effect {     public abstract void ApplyEffect(ICombatTarget target);   }
public class SlowEffect : Effect {
    [SerializeField] float slowPercent;
    [SerializeField] float totalTime;

    public override void ApplyEffect(ICombatTarget target) {
        target.speedMultis.Add(1 - slowPercent);
        Utils.RunAfterDelay(totalTime, () => target.speedMultis.Remove(1 - slowPercent));
    }
}
#

curious if something like this would be possible using [SerializeReference]

dusty wigeon
hardy sentinel
#

so would likely have to composite the classes with e.g.: enum in Effect? 😄

dusty wigeon
#

In fact, you will need to use [SerializeReference] if I am not mistaken.

dusty wigeon
hardy sentinel
#

wdym? 😛 the idea is to populate these lists with objects from the base types and serialize them

#

-- all while keeping Condition and Effect abstract

dusty wigeon
hardy sentinel
#

oh you mean it'd need to be like this:

public class Spell : ScriptableObject {
  [SerializeReference] private Condition condition;
  [SerializeReference] private List<Effect> effects
dusty wigeon
#

Yeah, but you will need to create a way to populate those field from the inspector.

hardy sentinel
#

oh if that's the only thing not supported out of the box that's quick to solve! thanks

#

in fact I never tried it.. I knew unity started supporting polymorphism in the inspector but by that time I was too deep in Odin to even give it a go

dusty wigeon
#

Odin Inspector must have a solution for that.

wooden cedar
#

Keep in mind Odin inspector also has a pretty unfavourable licensing

#

But yeah if you do decide to use it, I'm sure that's built in somewhere already

hazy epoch
#

Anybody know what happened to the Unity docs material explaining how to use Platform Specific Authentication for the Cloud Save services? All the links end in a Page Not Found error. They were just there last week.

hazy epoch
hardy nymph
#

How can I serialize a .meta file ?

#

I want to load up a meta file in the form of an object and convert it into a JSON string.

#

I can use the function Newtonsoft.Json.JsonConvert.SerializeObject(expected_object)

#

But expected_object needs to be the object (here meta file).

#

Or maybe my approach is wrong

#

I just need to load up a meta file and convert it into a json string

dusty wigeon
#

What are you even trying to do ?

hardy nymph
#

I need that JSON data so I can make edits to that JSON from an external source like a website and send it back the Unity , then Unity will update the .meta file according to that JSON.

#

Using EditorJsonUtility.FromJsonOverwrite I can overwrite an existing object.

dusty wigeon
#

And .meta files are not JSON, but YAML if I remember correctly.

hardy nymph
#

For-example this is meta file of a sprite

#

I can edit the sprite pivot

hardy nymph
dusty wigeon
#

This is YAML, not JSON.

trim rock
#

Anyone knows if animation layers work with Netcode for GameObjects (NGO)?

I have a Animator Controller with 3 layers, 1st for movement only, the other 2 are the same, attack combo layers, but they use different Avatar Masks if the character is moving or not.
Thing is, the layers are not working when I change the mask weight when using NGO.

I tried debugging changing to a near identical Animator Controller, except this one has just 1 layer with everything the other 2 layers have inside, and no Avatar mask is used. It works like a charm, but obviously the animations and the experience is nowhere near the same.

So, anyone knows if they work with NGO?

dusty wigeon
trim rock
#

Ah, you are right, I didn't saw the networking channel, I'll ask over there, apologies.
In regards to your question: I'm using a client based animation sync approach with:

protected override bool OnIsServerAuthoritative()
{
    return false;
}

And managing the animator parameters locally on each client. The only NetworkAnimator call I make is to .SetTrigger, as the documentation says.
With only that, layers don't work, and I'm not getting any logging either.
As I mentioned earlier, when I change to a single layer approach, everything works as expected.

dusty wigeon
#

Oh, I did not know Netcode had a NetworkAnimator. It seems a bit strange too me.

trim rock
dusty wigeon
trim rock
#

Oh, interesting, I'll try that, thank you!

trim rock
#

@dusty wigeon It worked! Thank you for your suggestion!

kindred remnant
flint quest
#

Is there any trick to get data into a baker other than the authoring script? I tried to pass stuff in via a DontDestroyOnLoad singleton, but it can't seem to find it. I'm trying to populate a buffer with GetEntities(prefab) to be instantiated later.

#

An alternative to this would have a SystemBase read from the singleton, but I can't seem to find the equivalent of GetEntity(gameObjectPrefab) that Bakers provide to use within SystemBase::OnUpdate().

dapper cave
#

who here is using kd-tree to speed up proximity search? seems overkill vs loop through distance and wanted a second opinion

dusty wigeon
dapper cave
compact ingot
novel nacelle
# dapper cave who here is using kd-tree to speed up proximity search? seems overkill vs loop t...

I have used it before, it depends on the number of objects you're comparing to (and dimensionality). k-d tree is O(logn) for the depth of the tree as opposed to brute force checking of O(n^2). At larger number of objects it's can be significantly faster, but I probably wouldn't use it for comparisons of less than 20 objects. 20 objects = 400 comparisons per second. 1000 objects = 1,000,000 comparisons per second.

#

not per second, per loop or whatever

dusty wigeon
# dapper cave it's not a static point of cloud, more like your usual closest object query in a...

I mean, what you are trying to do. Specifically.

Does it runs every frame ?
Is it closest pair of points or closest point ?
Do you need to check every point or can you check every point in the Area ?
Can you cache the results and reuse it ?
Can you spread the operation on multiple frame ?

For 1000 objects, depending if this is for nearest point, this is not that much expensive. (1000 operations) If you are targeting PC, you will not even feel the operation same if it is done every second.

steel snow
#

@hardy sentinel@scenic forge i did my Run() testing, it seems .Schedule() costs my performance 🤔

#

see comparisons here

#

Schedule takes a whole 5ms

#

taking up 10% of the full algorithm time

#

resulting in it being slower than main thread

untold moth
#

Well, scheduling 421 jobs at once does sound crazy to be fair. Perhaps split the work into less jobs that do more work.

scenic forge
#

Perhaps I'm missing your setup, why would you need to .Run() and .Schedule() 421 times?

#

Are you just repeating the entire algorithm 421 times for the purpose of profiling, or does one run of your algorithm actually need to do the same thing 421 times?

#

If the latter, then it really should be part of your jobified algorithm instead, so it's only running/scheduling once, rather than eating the fix cost of job system 421 times.

scenic forge
#

In case I didn't make myself clear, assuming your algorithm is (pseudo code):

for i in 421:
  for j in 500:
    DoWork(i, j);

The correct way to parallelize it would be:

schedule parallel job i in 421 * 500:
  DoWork(i / 500, i % 500);

The incorrect way (which seems like what you are doing) would be:

for i in 421:
  schedule parallel job j in 500:
    DoWork(i, j);
steel snow
#

unity docs had a function example on calculating nice batch sizes automatically

#
        private static int GetBatchSize(in int arrayLength)
        {
            int numBatches = math.max(1, JobsUtility.JobWorkerCount);
            return arrayLength / numBatches;
        }
#

but it only saved me about 10fps

steel snow
#

deluanay algorithm

scenic forge
#

Then that's the incorrect way to parallelize it.

untold moth
steel snow
#

i see

scenic forge
#

You really have to figure out a way to parallelize it in the way of second code block

steel snow
#

does such an algorithm work well on a gpu ? i presume not

scenic forge
#

Otherwise you are just repeatedly eating the fix cost of job system.

steel snow
#

so is my cost simply creating too many threads ?

untold moth
steel snow
#

i have a list of vertices and im creating a mesh from it via deluanay algorithm

#

well random points*

untold moth
#

Kinda like marching cubes?

steel snow
#

no no just a 2d flat plane

#

this is how it looks

#

thats around 50 random points that runs at about 70fps

untold moth
#

I'm not accustomed with the deluanay algorithm, so not sure if it's possible to adapt it to GPU. Maybe try googling that?

scenic forge
#

I don't know about the specific algorithm in particular, but yeah your problem is simply the incorrectly parallelization of it.

steel snow
scenic forge
#

If you can parallelize it into one loop deep, that should solve all your problems.

steel snow
#

one loop is a bit difficult the algorithm has a lot of loops

#

i basically made these into jobs:

scenic forge
#

Perhaps only parallelizing the outer loop, while leaving inner loops single thread.

steel snow
#

i cant because the outer loop depends on the previous iteration

#

as it shares the triangle collection

untold moth
steel snow
#

yeah but there are those inner for loops which are not incremental

#

so i thought to parallel those

scenic forge
#

And you will be eating the fix cost for each of those inner loops

steel snow
#

but im guessing the outer incremental loop is spending a lot of time waiting for threads to be scheduled and complete that it ends up no faster

scenic forge
#

Even outside the context of Unity and Job system and in a context of a native program, spinning up native OS thread is also massively costly.

#

Parallelizing algorithms can't just blindly turn every for loop into multithreaded.

steel snow
#

ah i see

#

didnt realise it was quite that expensive

untold moth
#

If you need a lot of separate small jobs done it's definitely more suitable for a GPU.

steel snow
#

yeh i might try a gpu approach

#

though the cost to return the data from the gpu might not make it any faster

#

although i dont think compute would work because i need to write to buffers

#

so there would be race conditions

scenic forge
#

Well, transferring data in and out of GPU will be costly too so it's the same problem really

#

So if you have a big 421 outer loop, that for each iteration it transfers data in and out of GPU, that would just be the same problem but in a different flavor.

steel snow
#

for 500 points the loop can reach 25000+

#

its quite crazy

untold moth
scenic forge
#

Yeah, ultimately you just want to only eat the fix cost once.

steel snow
#

oh it has concurrent writing support?

untold moth
#

There's the append buffer. The only problem is that it wouldn't have any guaranteed order, but that's manageable.

steel snow
#

thats fine as i dont require ordered data

scenic forge
#

NativeQueue is the equivalent on the CPU side.

untold moth
#

Reading the data from the GPU has an overhead, but definitely not as much as you get now. It wouldn't be any higher than 1 Ms imho. Probably a lot less even.

scenic forge
#

Multithreaded, append only, no order guaranteed.

untold moth
#

And if you want to optimize further, you can modify the vertex buffer itself on the GPU without needing to move data back to CPU.

scenic forge
#

Incremental algorithms can still be parallelized depending on the nature of it.
A classic example being summing a list of numbers, on the surface it seems like it can't be parallelized, each chunk of work must depend on the result of previous chuck:

foreach (var num in nums)
  sum += num;

However, there is still a parallelized algorithm for it:

// main thread
var (nums1, nums2) = Partition(nums, 2);

// thread 1
var sum1 = Sum(nums1)

// thread 2
var sum2 = Sum(nums2)

// main thread
var sum = sum1 + sum2

And this is basically what Amdahl's law is talking about: notice how the work done on main thread cannot be parallelized further, so there's an upper bound to performance increase as you keep adding threads.

In general parallelizing an algorithm follows a similar approach:

  • Partition: split total work into multiple smaller chunks of work independent of each other.
  • Threading: spin up threads to perform on each chunk of work.
  • Merge: combine results from each smaller chunks of work to yield final result of the total work.
leaden sandal
#

How do I make a line renderer appear on a render texture? When rendering a cameras view line textures aren't rendered. I have done extensive research on this but I can't find a solution. Anyone have any ideas?

untold moth
untold moth
#

Hmm

#

Can you take some screenshot of the setup as well as of the camera preview with the line renderer visible and the render texture with it not visible?

leaden sandal
#

I partially fixed it, switching the background of the camera to solid color and making transparency 0.5 makes it show up but you can still see surrounding black. Ill send a ss now

leaden sandal
#

I am trying to make a line render work in 2d space

#

as that is not a feature provided with unity

#

and the only plugin for it was from 7 years ago and is broken

#

Here is a more easily understandable screenshot:

#

I am trying to render a line between these two ui elements in 2d space

untold moth
#

Can you open the LineRendererTexture in the inspector and take a screenshot?

leaden sandal
untold moth
#

Not that. Read my message again.

#

What I asked for is the inspector of the render texture.@leaden sandal

sand acorn
#

Hello there, I am trying to make chunk generation like minecraft following a tutorial, the code works as expected except for 1 small detail which is the chunk also renders inner faces (look at the picture below); I have seen this guy used a try and catch where try renders only the surface of the terrain with some missing faces and catch renders the missing faces but adds more unncecesary faces inside the chunks. I have noticed this happens because some block positions result in being at negative indexes so the loop just doesnt get there. Any ideas on how to fix this? should I refactor the code instead?

#

https://hatebin.com/rwwphgjucb here is my code, line 232 contains the catch thing that generates unwanted faces but fixes the gaps generated by the try statement

leaden sandal
#

@untold moth

untold moth
#

Ok, so it seems to render to the texture properly.

#

The issue is probably with how you then render the texture in the scene.

leaden sandal
#

yeah

#

I want to remove all the black

untold moth
#

Was that the problem all along..?😅

leaden sandal
#

no, it changed mid way through

#

I fixed the first problem

untold moth
#

To remove the black color, change the clearing flags on the camera to not clear I guess. Although...

leaden sandal
#

Like setting it to solid color and making background transparent?

sand acorn
untold moth
leaden sandal
untold moth
leaden sandal
#

continuously render itself without removing the previous frames render.*

leaden sandal
#

Like background color to completely transparent?

#

Because yeah when I set the cameras background to transparent both the line and background go transparent

sand acorn
#

@leaden sandal what are you trying to achieve on first place?

leaden sandal
#

I want a line between an origin position and my mouses position

#

on a ui canvas

sand acorn
#

Camera.main.ScreenToWorldPoint(Input.mousePosition); this line should work for you

untold moth
#

Yeah, ideally you'd just set the line positions to screen space.

sand acorn
#

What kind of behaviour are you having? I guess the line is not streetching / snapping correctly onto the mouse position, right?

leaden sandal
#

Like it happens in the physical location of the ui

sand acorn
#

Hmmm, have you modified this onto your canvas?

leaden sandal
sand acorn
#

Also, do you have your camera rotation at 0 on all axis or you have different values

#

I faced a very similar issue in the past where my line would never match the position of my mouse

sand acorn
#

the reason was that my camera rotation was not 0, it was something like 0,0, -90

untold moth
leaden sandal
#

thats why I am using a seperate camera to render the line

leaden sandal
#

The line will go to the mouse position in world I just want it to go to the position on a 2d plane

sand acorn
untold moth
#

If you want to keep it as a render texture, I'd suggest checking the frame debugger.

leaden sandal
#

I think I fixed it, by changing the line renders material from default line material to a custom material

untold moth
#

That's weird, but ok.

#

What material did you change it to?

leaden sandal
#

Just a new base material

untold moth
#

With the Standard shader?

leaden sandal
#

yeah

sand acorn
#

No idea why that fixes your render issue but glad it works

leaden sandal
#

oh damn

#

It works but now with different aspect ratios the cameras position is in the wrong place and gets messed up

#

16:9 works perfect but when the size of the canvas changes the position of the camera is wrong

untold moth
leaden sandal
#

I don't update it.

untold moth
#

Well, it wouldn't correspond to your actual screen resolution then.

leaden sandal
#

Yeah

#

oh yeah

leaden sandal
#

I found that if I move the camera to the center of the canvas and then move it away from the ui so it can see the lines its okay. But I have to manually set the z value based on screen size.

midnight violet
leaden sandal
#

I need to render a line render onto my screen

#

the overarching goal is for a ui element to be an origin point and to draw a line from that origin to my mouse cursor.

#

And for it to be infront of all other ui

#

and for it to be 2d in a 3d game

#

which only seems possible by doing it separately and using a render texture to overlay it onto the game

midnight violet
#

And attaching the linerenderer to the UI object does not work?

leaden sandal
#

yeah

#

Well it doesnt matter where the line renderer is

midnight violet
#

What is the canvas mode? Screenspace overlay?

leaden sandal
#

yeah

midnight violet
#

Apart from not being a coding question I guess, but whatev 😄

leaden sandal
midnight violet
#

So this is a linerenderer on an UI element

leaden sandal
#

Does it follow mouse pos?

midnight violet
#

Do you update the position in code?

leaden sandal
#

yeah

#

When I set the position of the line to be the ui element it starts as the physical position of the ui element

#

and I can't use screen point to world because that would be the position of the mouse in 3d space

midnight violet
#

So what should the line attach to exactly?

leaden sandal
#

the mouse position

#

There is a plugin made for what I'm trying to do but its only for 2019

midnight violet
#

this is following my UI element

#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

[ExecuteAlways]
public class LineRenderPointUpdate : MonoBehaviour
{
    public RectTransform rectTransform;
    public LineRenderer lineRenderer;

    private void Awake()
    {
        rectTransform = GetComponent<RectTransform>();
        lineRenderer = GetComponent<LineRenderer>();
    }

    private void Update()
    {
        if (!rectTransform || !lineRenderer)
            return;

        Vector3[] newPos = new Vector3[2];

        newPos[0] = Camera.main.ScreenToWorldPoint(new Vector3(rectTransform.position.x, rectTransform.position.y, Camera.main.nearClipPlane));
        newPos[1] = new Vector3(Camera.main.transform.position.x, Camera.main.transform.position.y, Camera.main.transform.position.z + Camera.main.nearClipPlane);

        lineRenderer.SetPositions(newPos);
    }
}
#

Is the result of the code above

hybrid belfry
#

Morning. Can anyone tell me why my last property is not being serialized in the Inspector? If I comment out the last Enum entry, the next last enum entry is no longer shown either. The list in Image 1 is the Props enum - sorry it cut off

midnight violet
hybrid belfry
#

Anyway I found the problem rookie error

midnight violet
hybrid belfry
midnight violet
hybrid belfry
#

Another issue with my Script I couldn't resolve yesterday - I'm making use of the OnBeforeSerialize() and OnAfterSerialize() callbacks from ISerializationCallbackReceiver interface to save the data in my 2D array. The problem is, OnBeforeSerialize runs constantly in the Editor and not just before any serialization occurs. This means I can never really "wait" until serialization is done before I work on the data. I'm using a bool check. Not sure if this is how these things work :/

hybrid belfry
#

Just before and after serialization (when I make code changes to script)

midnight violet
#

oh before makes sense, ye

#

So you are changing the 2d array in your code, not in inspector or via any runtime script, right?

hybrid belfry
#

Yeah I just read up that it is designed to run whenever changes are made for example OnDrawInspector() would cause it to run etc. So for example, it doesn't just run when a script needs recompiling which is what I thought it did

#

I'm changing the 2D array through the inspector

midnight violet
hybrid belfry
#

Sorry my mistake, I'm using OnDrawGizmos to draw the grid. In here I check if the grid needs recalculating. I could use OnValidate but it wouldn't solve the problem

midnight violet
#

Can you explain the dataflow for me probably? So you change the 2D Array, this fires the OnBefore and OnAfterSerialize?

leaden sandal
# midnight violet ```cs using System.Collections; using System.Collections.Generic; using UnityEng...
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class FixWireTask2 : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
    public RectTransform rectTransform;
    public LineRenderer lineRenderer;
    private bool ShouldCast = false;

    private void Awake()
    {
        rectTransform = GetComponent<RectTransform>();
        lineRenderer = GetComponent<LineRenderer>();
    }

    public void OnPointerDown(PointerEventData eventData){ShouldCast = true;}

    public void OnPointerUp(PointerEventData eventData){ShouldCast = false;}

    private void Update()
    {
        if(!ShouldCast)
            return;
        if (!rectTransform || !lineRenderer)
            return;
        Vector3[] newPos = new Vector3[2];

        newPos[0] = Camera.main.ScreenToWorldPoint(new Vector3(rectTransform.position.x, rectTransform.position.y, Camera.main.nearClipPlane));
        newPos[1] = new Vector3(Camera.main.transform.position.x, Camera.main.transform.position.y, Camera.main.transform.position.z + Camera.main.nearClipPlane);

        lineRenderer.SetPositions(newPos);
    }
}

``` I adjusted the code slightly to work with my project, I have assigned the rect trans and the line renderer. This is the only result.
#

@midnight violet

midnight violet
leaden sandal
#

Yeah, my other cameras are disabled

midnight violet
#

But are they all probably MainCamera, or only one?

leaden sandal
#

Only one is main camera

midnight violet
#

And you use SCreenspace.Overlay?

leaden sandal
#

Yes

midnight violet
#

Something is different then on your side, cause as you saw, its working on my side. can you show your sceneview of the linerenderer?

leaden sandal
#

Its just meant to be a base unchanged line renderer right?

#

or did you change yours

#

because mine is just base

midnight violet
#

yes it is. can you select your maincamera and show the sceneview?

leaden sandal
midnight violet
#

did you actually read my message? 😉

leaden sandal
#

Do you mean like this?

midnight violet
#

SceneView, where you move things 😉

#

The left one with your camera selected and focused

leaden sandal
#

and focused

#

okay hold up

#

There, I think thats what you mean

#

finally got there XD

midnight violet
#

Can you just set the nearclipplane to 0.3 just to have the same values like I do?

leaden sandal
#

Yeah I set it to .3

midnight violet
#

Oh well, if you use something like 0.01, you need to adjust the width of your linerendere,r but besides that it works on my side with 0.01 too

leaden sandal
#

btw the rect transform variable is just the object where the line starts right?

midnight violet
#

if the UI element

#

the array inupdate is just the positions you can set. so it can be any size

leaden sandal
#

Yeah

#

But the line starts at a the defined ui object and ends at the mouse position right?

#

Because I dont see anything in the code about that

midnight violet
#

No, there is no mouseposition included but you can figure that out yourself. Just instead of taking a recttransform position or anything, you just use the mouseposition

#

a recttransform is also in pixel space as well as the mouseposition

leaden sandal
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class FixWireTask2 : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
    public LineRenderer lineRenderer;
    public bool ShouldCast = false;
    public RectTransform OriginPosition;

    private void Awake()
    {
        lineRenderer = GetComponent<LineRenderer>();
    }

    public void OnPointerDown(PointerEventData eventData){ShouldCast = true;}

    public void OnPointerUp(PointerEventData eventData){ShouldCast = false;}

    private void Update()
    {
        Vector3[] newPos = new Vector3[2];

        newPos[0] = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.nearClipPlane));
        newPos[1] = new Vector3(OriginPosition.position.x, OriginPosition.position.y, OriginPosition.position.z + Camera.main.nearClipPlane);

        lineRenderer.SetPositions(newPos);
    }
}

``` This is what I've got rn
#

With that updated code I get this result.

midnight violet
# leaden sandal

Well the target lloks right, are you using the new or old input system?

midnight violet
#

you cant...

leaden sandal
#

You can

midnight violet
#

Alright, enjoy then.

leaden sandal
#

It says right there

midnight violet
#

rather proving you could, ask yourself why you would

leaden sandal
#

because for somethings its just easier to use the old one

midnight violet
#

Setting "Active Input Handling" to "Both" in the Player Settings will enable both to run side by side. Not supported on all platforms and not extensively tested/support but should generally work.

leaden sandal
#

but for others its better to use the new one

midnight violet
#

from forums

#

Just to be lazy in writing input.* thats the only reason. there is no other reason I know of besides that 😄

leaden sandal
#

yeah pretty much

midnight violet
#

Well, I tested my script with my input mouse binding and it works

leaden sandal
#

on new or old input?

#

old i assume

midnight violet
#

        mousePos = inputActions.Default.MousePosition.ReadValue<Vector2>();

        Vector3[] newPos = new Vector3[2];

        newPos[0] = Camera.main.ScreenToWorldPoint(new Vector3(rectTransform.position.x, rectTransform.position.y, Camera.main.nearClipPlane));
        //newPos[1] = Camera.main.ScreenToWorldPoint(new Vector3(targetRect.position.x, targetRect.position.y, Camera.main.nearClipPlane));
        newPos[1] = Camera.main.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, Camera.main.nearClipPlane));

You decide if you wanna stick to that old input. I used the new one

#

I never ever touch the old again 😄

leaden sandal
#

alr ill use the new

midnight violet
#

its for sure not advanced coding 😉 Do you have any code to checkout?

lament totem
#

yes

midnight violet
#

put it in general, might fit in there

lament totem
#

okay thanks

leaden sandal
#

@midnight violetCan you send a ss of your input map so I can make it like yours

#

I have never used the new input system

midnight violet
#

I suggest learning it. its easy to setup and comfortable to use 🙂

#

you also need to check in the asset to generate the c# file automatically

#

and in your script, or a global script, create a new YourInputAssetName inputAsset and use new (); and .Enable(); in awake to actually get the inputs in

leaden sandal
#

@midnight violetWhat do I put in here

#

Do I just leave it blank or what?

midnight violet
#

but maybe not name it input 😉 or disable the old input system, cause otherwise you run into naming conflicts

leaden sandal
midnight violet
#

InputAsset = new GameInput();

leaden sandal
#

Okay

midnight violet
#

you really should read into some unity tutorials, general c# and input system in specific. You are lacking some basic knowledge of how c# code is structured. no offence, just making yourself a hard time fiddling through premade code wont work out in the longterm.

leaden sandal
#

Its more that I don't know how to use the input system and I didnt know what you meant by new()