#archived-code-advanced

1 messages Β· Page 106 of 1

scenic forge
#

I'm not sure what it's supposed to do, but it seems like you are looking for the Foo<T> where T : Foo<T> pattern.

tropic vigil
#

The point is that I don't know the T.

upbeat path
scenic forge
tropic vigil
#
AttributeType at = new AttributeType<MyClass>();
---
object o = (object)at.ModifyAttributeValue();

This won't work since ModifyAttributeValue is inside AttributeType<T>. at in this case is the type of AttributeType. You can't use it like this unless you cast at to AttributeType<T>, but you don't know the T at the moment.

upbeat path
stuck plinth
#

hmm why do you want to call ModifyAttributeValue without knowing the type? that limits what you can do with the result quite a bit

tropic vigil
tropic vigil
scenic forge
#

I feel like some context is missing, might be a better idea to share your current code.

#

As I see it, your current implementation of ModifyValue in your non generic base class AttributeType cannot be safe without knowing T, yet the inherited generic class can make T be anything.

tropic vigil
# scenic forge I feel like some context is missing, might be a better idea to share your curren...

The concept is to create some system for generic attribute scriptable objects. Depending on the attribute, it could be int, float or something else. It worked nicely until I wanted to create an ability that transfers a value of some attribute from one object to another. E.g. you could drain enemy's health or mana. I think implementing such "transfer" functionality directly into AttributeType could do the job, but I was hoping for a solution that wouldn't require modifying AttributeType's code each time I want to create a new kind of effect.

fallow eagle
#

Why does not Burrito's solution work in your case ? I would assume that the operation made by ModifyValue() would change depending on the type of the object

#

you just want this, no ?

abstract class AttributeType<T>
{
    public abstract T ModifyValue();
}

class IntAttributeType : AttributeType<int>
{
    public override int ModifyValue()
    {
        // ...
    }
}
#

(Just trying to understand)

tropic vigil
fallow eagle
#

OK. Thanks, it's more visual that way haha

stuck plinth
#

i don't know exactly what you need but i guess you'd only need to put enough building blocks in AttributeType that you could implement more specific stuff in terms of those?

scenic forge
tropic vigil
dusty wigeon
pure berry
#

Hello, I'm trying to implement a StateMachine for my character's controls. I use rigidbody.
I need a basic class or interface from which to derive the various states my character will be in. But I've run into a dilemma.
In your opinion, is it better to use an abstract class or an interface to define a State Machine ?
From what I've seen on the internet, it's the interface that comes up most often. But the tutorials on the iHeartGameDev YouTube channel, which I think are very good, use an abstract class.
What do you think I should choose ?

upbeat path
#

An interface only makes sense if you have multiple characters which each implement their own behaviours

stuck plinth
pure berry
pure berry
upbeat path
stuck plinth
upbeat path
#

@pure berry If you have only one Character that needs a State Machine then the question of Interface or Abstract class does not even arise

pure berry
pure berry
pure berry
upbeat path
stuck plinth
upbeat path
tropic vigil
pure berry
upbeat path
dusty wigeon
pure berry
pure berry
stuck plinth
upbeat path
# pure berry If when you say "State data structure" you're referring to the way we manage the...

OK, I misunderstood what you were trying to do. There is no reason not to use both Abstract and Interface. What I would do is evaluate where the commonalities are. For those states which have much in common implement them in an abstract class, for those with little or no commonality implement them in an Interface. But as @stuck plinth says, there is really very little conceptual; difference

#

Basically if you find yourself duplicating code you have chosen the wrong path

pure berry
pure berry
#

Thank you very much @stuck plinth and @upbeat path . It was really helpful. Have a nice day ! 😁

tropic vigil
# dusty wigeon Yes, but what is the data structure that holds that ? Do you hold your object in...

Allright, lets do it the hard way:

[CreateAssetMenu(fileName = nameof(TransferAttributesEffect), menuName = "Interactions/Effects/TransferAttributesEffect")]
public class TransferAttributesEffect : InteractableObjectAlterationEffect, ICellInteractHandler
{
[SerializeField] AttributeType [] attributeTypes = new AttributeType[1];
[SerializeField] AttributeType.ValueType valueType = AttributeType.ValueType.currentValue;
[SerializeField] Modifier [] modifiers;
[SerializeField] TargetConverter targetReceiverConverter;

public override void InteractWithTargets(IInteracter selectedSource, InteractableCell[] selectedTargets)
{
  var covertedTargets = GetConvertedTargets(selectedSource, selectedTargets);
  var transferReceivers = targetReceiverConverter.ConvertTargetsToInteractables(selectedSource, selectedTargets);
  foreach (var covertedTarget in covertedTargets)
    foreach (var transferReceiver in transferReceivers)
      foreach (var attributeType in attributeTypes)
        attributeType.ModifyAttributeValue(transferReceiver, valueType, - attributeType.ModifyAttributeValue(selectedSource, covertedTarget, valueType, modifiers, multiplier));
}
}

I just have a bunch of AttributeTypes and I try to use their generic value as an argument for another generic method from the same AttributeType. I don't know what T I'm ending with, but I'm sure it's the same as AttributeType's T.

dusty wigeon
#

It seem like you handle the type without actually using the type. By using an enum.

tropic vigil
dusty wigeon
#

What is the attribute type ? Float, Integer, etc. ?

tropic vigil
dusty wigeon
#

Why are you not using something like Modifer<int> ?

tropic vigil
dusty wigeon
#

So, your AttributeType is what define the operation ? Like summation, division, etc. ?

tropic vigil
dusty wigeon
#

So, your modifier defines the operation to be executed and the AttributeType is the one actually executing it ?

tropic vigil
tropic vigil
dusty wigeon
#

So, attribute type represent Health, Mana, etc. ?

tropic vigil
dusty wigeon
# tropic vigil Yep, stuff like that.

I am not sure why the AttributeType is not directly linked to the Modifiers.

By example, (Obviously, not exactly that)

public class Modifier<int>
{
  [SerializeField] private AttributeType<int> attributeToModify;
  [SerializeField] private int value;
  
  public void Execute(Context context)
  {
    Target target = context.GetTarget();
    Attribute<int> attribute = target.GetAttribute<int>(attributeToModify);

    attribute.Add(value);
  }
}
#

The issue seem to be that you have two different Type which could be different (Impossible to know at compile time).

#

You would either need to restrict further at compile time or make runtime validation/cast.

tropic vigil
# dusty wigeon The issue seem to be that you have two different Type which could be different (...

Currently, I'm just casting it if needed (to calculate percentages I need floats anyway). I'm using numeric values, so there are no issues so far. But in the case of other types, I suppose I will simply make separate methods and call them (e.g. in Vector2AttributeType I would call Modifier.Vector2Fraction (IInteracter selectedSource, IInteractable selectedTarget, Vector2AttributeType attributeType) instead of Modifier.FloatFraction (IInteracter selectedSource, IInteractable selectedTarget, AttributeType attributeType)).

dusty wigeon
tranquil terrace
#

im writing my own transform / physics system for a fighting game, because i cant use unity's float based transform system for calculations. i was thinking of making a base class "entity" which would store the positions and velocities of an object such as a player or projectile. I'm just wondering what else I should store, if anything?

soft moon
tranquil terrace
silent dagger
#

Hello there...

#

I need some math smart guy because I'm lost πŸ˜…

#

Hello there πŸ™‚
I'm trying to make a sort of solar system, but the game is based on a grid, so I'm using this to calculate the position for each planet

for (int i = 1; i < celestialBodies.Count; i++)
 {
     float angle = CalculateOrbitPosition(celestialBodies[i], currentDate);

     float distance = cellSize * (i);
     float x = centerX + distance * Mathf.Cos(angle);
     float z = centerZ + distance * Mathf.Sin(angle);

     celestialBodies[i].celestialBodies[0].transform.position = new Vector3(x, 0, z);
 }```

But the problem is that I have to keep the planets centered on a 2D Grid... which is "virtual" because I won't use trigger.
So the cellSize defines that theorical cube, and I've stored it in a bidimensional int [,] ... any advice? πŸ™πŸ˜…
Ok... I know the center of the grid, so if  `i` = 1 define also the cell closer to the center which is the sun ...  and here I'm lost πŸ€”
sly grove
silent dagger
#

πŸ˜…

sly grove
#

but if you want a grid based game I would highly recommend Unity's Grid component

#

it will take care of all conversions to and from grid coordinates/world space and is freely configurable

silent dagger
#

I'm making object orbiting around an object, but I want that are snap to a grid

sly grove
#

that's very confusing

#

I can think of at least two different ways to do it though.

  1. You might have a "real" position with full floating point fidelity, and when drawing the things on screen you just snap the position to a grid for presentation purposes.
  2. You reimagine the concept of "orbit" in a grid-based setting which means throwing physics and such out the window
soft moon
silent dagger
#

I need the planets switch from cell to cell, should follow the orbit, but stiked to the center of the cell.

sly grove
# silent dagger

I'm unclear about what you mean about them "sticking" to the center

#

if they stick to the center, they will not be orbiting

#

Is it more that you just want to be able to identify which grid cell they are in?

silent dagger
#

sticked to the center of the cell. πŸ˜…

sly grove
#

and let them have a normal orbit?

#

Because otherwise, this just makes no sense to me

silent dagger
#

yea!

sly grove
#

Well as mentioned, just use the Grid component

silent dagger
#

Ok I will investigate on the grid component not even know that exists

sly grove
silent dagger
#

Ok I'll start studing it thank you πŸ™‚

#

Sorry for my bad explanation, but I'm Italian and my English sux a lot πŸ˜…

sly grove
#

(this isn't really an advanced code question by the way)

silent dagger
#

I was expecting some complicated array and trigonometry stuff πŸ˜›

tranquil terrace
soft moon
tranquil terrace
#

i need to make my own physics for this case

tranquil terrace
soft moon
tranquil terrace
#

yeah

soft moon
tranquil terrace
#

they are not cross platform deterministic, which means different machines may have different results for a simulation.

soft moon
#

Why does everyone still use Unity's physics?

tranquil terrace
#

for their case its probably fine, but im doing online multiplayer eventually so i need bit-perfect simulations across any platform

#

apparently πŸ˜…

soft moon
#

I think you should reconsider it

#

I wonder whether you'll be able to recreate Unity's physics, even party, in a better way than Unity has done it. Also, this may take quite some time, especially, if you're asking for the hints from the start

#

I'm also not sure whether you have already tested this calculation impact across different platforms

tranquil terrace
soft moon
silent dagger
molten minnow
tranquil terrace
molten minnow
tranquil terrace
molten minnow
rugged radish
#

most of fighting games are p2p (if not all of them), and don't involve physics simulation at all

tranquil terrace
#

wdym? stuff like moving up and down? im doing a platform fighter as well, with some projectiles that are affected by gravity

rugged radish
#

oh, a platforming fighting game, not too familiar with those
traditional fighting games operate exclusively on animation frames

molten minnow
sly grove
tall ferry
tranquil terrace
#

you dont have direct control of the character itself, as well as its position

molten minnow
tranquil terrace
tall ferry
molten minnow
#

Client will receive a state of the opponent, so it shouldn't be a problem to also get it's own state

tranquil terrace
molten minnow
tall ferry
tranquil terrace
#

which is why i wanted to give it a go

tall ferry
tranquil terrace
#

i know im oversimplifying it a bit though πŸ˜…

tall ferry
#

Have you looked into what other games, similar to what you're making, are doing for such a system?

#

A lot of fighting games systems are well known/somewhat documented

tranquil terrace
tall ferry
tranquil terrace
#

my idea is that i'll calculate the mvoement in fixed point system, and then show the transforms in unity's system

#

seperating the simulation from the visual or whatever

solar valve
#

Hello everyone, I am currently trying to work on a school project with some friends of mine. We want to recreate a game map on unity HDRP. The issue I am running into is that the base project of HDRP is already 2GB. Which makes it so that when I want to push to unity, to work collaboratively. I get an error from it, for it being too big, I believe the maximum is 50MB or something. I have made a bit of reserch, and there seems to be something called LFS that might help, but it seems that to use it, I need to use Git Krakern's terminal which I am not that experienced in. Anyone that could help with this?

swift orchid
solar valve
swift orchid
#

You can sort big files into one folder and ignore that folder, and copy that folder in google disk to share with friends, but it will work only if it is some static things for example 4k texture

sly grove
#

show a screenshot of your repository

bitter crescent
#

Hi everyone, can I promote my Unity package here?

sly grove
#

just the root directory

solar valve
#

How do i get hdrp in my project without, starting up with the base unity hdrp project?

sly grove
#

I don't care about the commit

sly grove
#

but - show the files in your repo

#

you can just take a screenshot of the repo from github

solar valve
sly grove
#

and the Temp folder

#

so you screwed up making the repo

#

that's why the repo is so large

solar valve
#

So the git ignore is not doing anything?

sly grove
#

You probably added gitignore AFTER committing the library folder

#

or you just didn't set up an appropriate gitignore file

solar valve
#

hmmmmm okay okay

sly grove
#

the easiest thing to do here will be to just delete the repository and create it fresh

solar valve
#

but you say that if i just start a normal unity 3d project, and then just add the hdrp package. my project then converts into an hdrp project?

solar valve
swift orchid
#

You will need to setup harp properly

sly grove
#

don't see any reason to do it that way

wet sail
#

hello. why does GPU Instancing not cause any performance boost? im spawning 65k cube, with standard material and "GPU Instancing" ticked on. i get the same 7-10fps.

wet sail
#

where do i post ?

sly grove
steel snow
#

bit confused i tried to replicate some code from unity's documentation and its not working in my test script. im trying to load an asset reference if the field is set like so:

public class LoadWithReference : MonoBehaviour
{
    [SerializeField]
    AssetReferenceT<MeshAsset> _meshAssetReference;
    MeshFilter _meshFilter;
    MeshRenderer _meshRenderer;

    void Awake()
    {
        _meshFilter = GetComponent<MeshFilter>();
        _meshRenderer = GetComponent<MeshRenderer>();
        if (_meshAssetReference != null)
            Set(_meshAssetReference);
    }
    public void Set(in AssetReferenceT<MeshAsset> assetReference)
    {
        if (_meshAssetReference != null) //release if already set
            _meshAssetReference.ReleaseAsset();

        _meshAssetReference = assetReference; //set it again
        AsyncOperationHandle<MeshAsset> handle = _meshAssetReference.LoadAssetAsync<MeshAsset>();
        handle.Completed += OnCompleted;
    }
    private void OnDisable()
    {
        if (_meshAssetReference != null && _meshAssetReference.IsValid())
            _meshAssetReference.ReleaseAsset();
    }

    //...etc
}

currently the field is not set and yet when i press play i get:

UnityEngine.AddressableAssets.InvalidKeyException: Exception of type 'UnityEngine.AddressableAssets.InvalidKeyException' was thrown. No MergeMode is set to merge the multiple keys requested. Keys=, Type=MeshAsset
OperationException : ChainOperation failed because dependent operation failed```


The error points to this line `AsyncOperationHandle<MeshAsset> handle = _meshAssetReference.LoadAssetAsync<MeshAsset>();`

Which i don't understand, why is  that function even occurring since the field is not set so it should be null πŸ€”
sly grove
steel snow
#

but shouldn't != null be sufficient?

#

the field hasn't been set to anything in inspector

#

it inherits from Unity's Object so it should be able to be null right?

sly grove
#

nvm I'm wrong it's not

#

but still

#

it's not going to be null

#

it's just going to be invalid

#

Unity serializer doesn't leave things null

#

And it doesn't inherit from UnityEngine.Object.

steel snow
echo venture
#

Hey guys, what is the best way to find the root cause of this issue?

long ivy
#

did you extract a stack trace? That would be the place to start

#

There's a utility under Tools in your screenshot to do it, and instructions in the logcat docs

honest hull
#

Is there a way to automatically call reimport on a bunch of comoute shaders to recompile them every time I change a line In a Cginc they use?
I know unity is supposed to handle it automatically but I’m running into a massive issue that makes compute shaders fail to recompile automatically, forcing me to reimport them all manually: #archived-shaders message

honest hull
#

nvm sorry, figured out that setting the shaders all to use the platform preprocessor fixes it

vale spindle
#

Hello. I'm working on a 3D character controller. Right now I'm not using rigidbody or collider, movenet is only done through scripts. The colliding is done via raycasts (its a cylinder collider). Might sound stupid but I need it this way to have full control over player's surroundings and velocity. So i'm just modifying the transform every frame. It works, but sometimes i clip through objects (as expected). I could easily add the collider and fix it, but i dont want to because i dont need it. What should i do?

#

The alternative would be to add rigidbody and collider back, but instead not use the raycasts. But i need them to get surface normals. Maybe there's some other way? OnCollisionEnter doesnt cut it

winged olive
#

Hello, since yesterday when I press the ctrl key my scene blinks and it prints this in the console, Im using Unity 6 Preview

glass anvil
#

I'm re-writing my managed voxel renderer to use jobs for both the data and rendering itself.

I populate a collection (I've tried NMHM which required a huuge capacity due to collisions(?) like 10x the known worst case), NHM, now NL)

with this collection I can sample the noise of any voxel values neighboring the chunk border. This way I can clip chunk borders without needing to know anything about/load the neighbor chunk itself.

I schedule that to run and when it's finished I chain the render job to it..

I use .AsParallelWriter when writing the skirt, and AsParallelReader when reading the skirt. I've also tried a normal writer/reader.. but I'm guessing if I want it to work correctly in a IJobFor it needs to be parallel?

The problem is with the attached photo. I've debugged the positions and made sure the skirt values are correctly encompassing the entire chunk.. but for some reason here it's only picking up some values?

        private IEnumerator RegenerateRoutine()
        {
            _chunkDataJob.Skirt.Clear();

            _chunkDataJobHandle = _chunkDataJob.Schedule(ChunkSize, 1);
            
            // bad to call immediately? negates parallelism
            while (!_chunkDataJobHandle.IsCompleted)
                yield return null;

            _chunkDataJobHandle.Complete();

            // Provide render job with the new data
            _chunkMeshJob.voxels = _chunkDataJob.Voxels;
            _chunkMeshJob.skirt = _chunkDataJob.Skirt;
            _chunkMeshJobHandle = _chunkMeshJob.Schedule(dependsOn: _chunkDataJobHandle);

            // bad to call immediately? negates parallelism
            while (!_chunkMeshJobHandle.IsCompleted)
                yield return null;

            _chunkMeshJobHandle.Complete();
            
            // advanced mesh api (much faster(?))
            _chunkMeshFilter.mesh.SetMesh(this);
            _chunkMeshCollider.sharedMesh = _chunkMeshFilter.mesh;
        }
#

Very new to jobs/burst but I've been learning a lot on github, the chunk itself is rendering fine without using any parallel writing, it's only when I try to write/read do I get this jagged appearance.. I know my face culling logic in the renderer itself works as this is based on a managed version. It definitely seems like the collection isn't writing, or reading the right values

glass anvil
#

to be clear the mesh job is just an IJob, the data is IJobFor which makes sense for it

untold moth
glass anvil
#

(totally, just trying everything I can at this point)

untold moth
#

What does your job look like?

#

Just share the whole file correctly. Upload to a paste site. !code

thorn flintBOT
untold moth
#

A bit too complex to find the issue by just looking at the code. I'd step through the code with a debugger and confirm that all the values and calculations are what you expect.

rapid owl
#

Hi all,

Am using URP and seem to be having some trouble passing depth to my compute shader, I have called:

        _computeShader.SetTextureFromGlobal(_kernel, "depthTexture",  "_CameraDepthTexture");

And also enabled depth in my URP options and end up getting "Property (depthTexture) at kernel index (0) is not set"

Does anything else have to be enabled? I checked the frame debugger and it seems like something exists at least

(Not sure what the right channel for this was so apologies)

untold moth
#

Most likely a race condition

untold moth
#

Then debug it. If there's a racing condition, you're probably writing to the same index ranges from several threads. Confirming the values and indices involved with a debugger would help you identify that.

untold moth
#

Speculating is not gonna help. You should debug properly.

untold moth
#

Why can't a debug log be helpful? It totally can. And If it really doesn't, then stepping through the code, or using log breakpoints can.

#

Of course you can

#

This is just code running on separate threads. You just need to disable the burst compiler

#

And weith some tinkering you can probably even debug burst compiled code

#

If you don't know how to debug properly, then ask about that, instead of expecting people to run your code in their heads to find the issue.

visual shard
#

hello can someone help me in putting ads in my game i have no experience in it and tried several times from many documentations and videos but never succeded if someone has done it and wants to help, DM me i'd be very gratefull

soft moon
oak spire
#

Can anyone help me do to damage model for flight sim?

lament salmon
#

I doubt anyone is going to go "yes sure, I will help you build the entire system"

oak spire
#

I want to know how it works. Any documentation or something.

#

so I can implement myself

plucky ridge
#

hey all, is there anyway to programmatically add new agentTypes for the NavMeshSurface component baking? I know I can define it using the editor, but i would like to programmatically create agentTypes so i can loop through and re-bake terrains during the runtime.

long cloud
#

Hi everyone. I need help with Coroutines and web requests. I need the script to return data for other scripts to run. Is this possible? If so how?

long cloud
#

I also don't want the frame held when doing the web request

soft moon
long cloud
#

I need a script that will request data from my website like version codes, ect. I want this scriptr to be callable by other scripts to get data when needed

compact ingot
soft moon
long cloud
compact ingot
#

Maybe ask a more specific question. The docs have a non-blocking coroutine example for a get request

long cloud
#

Problem solved thanks to Opera's Aria

worldly pecan
#

Hey guys, I have a C# question;

I have a list of structures, which I want to author and then put onto unmanaged memory(for jobs & stuff). I plan to do this by malloc-ing space for each structure and then maintaining a native array of pointers to these structures. These structures need to implement certain functionalities, defined by an interface. In managed-memory I author this as a list of interfaces. However to convert this to a pointer to unmanaged memory I run into some problems.

  1. Firstly, to malloc memory I need to know the underlying type. I guess there might be a way with reflection.
  2. Secondly, to get data from the pointer in a job I need to cast it back to the underlying structure. Interfaces are managed objects so I can’t cast it to an interface pointer unless I make the interface unmanaged somehow.

Are there any workarounds to this problem? Perhaps a different way to get structs to inherit functionalities so I can call them without knowing their specific type?

sly grove
worldly pecan
#

Like if I had an interface for a car(ICar) I can have a list of cars called List<ICar> in which I guarantee all of them have the same basic functionality--I just need to translate this to unmanaged memory.

sly grove
worldly pecan
sly grove
#

unless you keep a separate dictionary of pointers/offsets into it

#

oh they're pointers

worldly pecan
#

the memory scopes aren't the same size though, but they don't need to be (I don't think so fundamentally)

sly grove
#

do you really need them to be different structures? It might be better to make a struct that's a union of them all and just make an array of those

#

with an enum flag or something denoting the type

#

basically - don't try to force polymorphism into the native world

worldly pecan
sly grove
#

how much is "a lot"?

#

and how many things will there be

#

and if so - you could store that extra data in a separate collection if those things are rare

scenic forge
#

If size is a concern, your struct can very well be just a tag and a pointer to another struct that contains more data for the specific type.

worldly pecan
#

I'm trying to do this for some entities(like animals). They have different behaviors and different stuff they need to keep track of. A certain animal needs to keep track of different data & different amounts of data than another animal.

#

I mean... fundamentally I should be able to malloc different sizes and store their pointers in a native array to use them in a job

sly grove
#

yes you fundamentally could but the things that are good for performance are not necessarily things we normally consider "clean"

#

there are large performance advantages to having all your data in a single colocated array rather than all over the place with pointers and malloc'ed locations

scenic forge
#

It's also just two different ways of writing the same code.

sly grove
#

Basically all the things that make OOP and polymorphism nice are actually anathema to performance and how computers actually work

rugged radish
#

I have something similar in my code. But instead of structs I store values in a big number of arrays for jobs / compute shaders. And in managed code I use a number of "view" classes and manipulators that change the underlying arrays directly.

worldly pecan
rugged radish
#

yeah, I went pretty much data oriented with oop convenience

upbeat path
worldly pecan
upbeat path
#

Unity docs have a complete section on it

worldly pecan
upbeat path
solid magnet
#

Hi, I have a game with levels and I have an editor inside the unity editor to make them but I don't know where to save them (I don't want/can't save them in different scenes etc...). I want to save them in a json (it's actually just some lists of points), problem is idk how to create a json file inside of the assets folder neither how to access it (the path), how do I do that? Or is there a better way than json to save lists of vector2D/bools/in

sly grove
solid magnet
upbeat path
solid magnet
#

Thanks

upbeat path
solid magnet
#

That's what I'm doing πŸ™‚

scenic forge
# worldly pecan This is like completely abandoning OOP, I mean I could try something like that

It's honestly just two different ways of writing code, if you are deep in OOP you might have only worked with the OOP way:
(The following codes are in TS because C# doesn't have real nice union, but the examples are just to demonstrate how to write the exact same code in two different ways)

type Shape = {
    calculateArea(): number
}

class Circle implements Shape {
    constructor(
        private radius: number
    ) {}

    calculateArea() {
        return Math.PI * this.radius * this.radius
    }
}

class Rect implements Shape {
    constructor(
        private width: number,
        private height: number
    ) {}

    calculateArea() {
        return this.width * this.height
    }
}

const circle = new Circle(42)
const rect = new Rect(42, 69)
circle.calculateArea()
rect.calculateArea()
type Shape =
    | { type: 'circle'; radius: number }
    | { type: 'rect'; width: number; height: number }

function calculateArea(shape: Shape) {
    switch (shape.type) {
        case 'circle':
            return Math.PI * shape.radius * shape.radius
        case 'rect':
            return shape.width * shape.height
    }
}

const circle: Shape = { type: 'circle', radius: 42 }
const rect: Shape = { type: 'rect', width: 42, height: 69 }
calculateArea(circle)
calculateArea(rect)

The first way fundamentally relies on dynamic dispatch, which C++ implements it as virtual function table. If you want to get that in your native code, you will have to basically reinvent it yourself.
The second way however does not require that.

#

OOP encapsulates data and behavior together into classes, whereas functional separates them into plain data (with no behavior) and free functions operating on those data (behavior). It's not too difficult to change your code between the two styles once you understand them, and the functional style works a lot better with the constraint of Burst.

worldly pecan
scenic forge
#

You can, by basically reinventing dynamic dispatch yourself.

#

Burst supports function pointer, so instead of IFoo with a method DoFooThing(), you would have a Foo struct with two fields, one is a pointer to the data, and one is a function pointer. And calling DoFooThing would be calling the function pointed by the function pointer, with the first argument being the data pointer.

solid magnet
#

levelData is a ScriptableObject class, this script is not from runtime but it's only runned manually from the editor.
How can I make the values be permanents? I want them to still be available when I start the game

    public void SaveLevel(){
        if(levelData.levelPoints.Count >= level){
            levelData.levelPoints[level-1] = path.points;
            levelData.obstacles[level-1] = new List<Vector4>{};
            levelData.end[level-1] = new List<Vector3>{};
            levelData.levelType[level-1] = "default";
            levelData.minimumDriftDuration[level-1] = 0f;
            levelData.isNight[level-1] = false;
            Debug.Log(levelData.levelPoints[0][1]);
        }
        else{
            levelData.levelPoints.Add(path.points);
            levelData.obstacles.Add(new List<Vector4>{});
            levelData.end.Add(new List<Vector3>{});
            levelData.levelType.Add("default");
            levelData.minimumDriftDuration.Add(0f);
            levelData.isNight.Add(false);
        }
    }
worldly pecan
#

I don't recommend using Scriptable Objects to save data, but if you are--I believe it's something along the lines of
EditorUtility.SetDirty(scriptableObj);
AssetDatabase.SaveAssets();//
AssetDatabase.Refresh();

You should really save in another format though. Scriptable Objects are mostly for settings and shouldn't be changed

solid magnet
#

Anyway, thanks for the help

solid magnet
worldly pecan
#

When you want to update your asset. You can think of your instance being a copy of the scriptable object, and when you call that it copies it back. That's not really what it is but it's close enough in effect

solid magnet
#

Ok I'll try that

#

thanks

upbeat path
worldly pecan
#

put this
using UnityEditor;

solid magnet
#

Thought I had it sorry

#

Got another problem (kinda related)

#

It only saves part of the data

#

I have problems with this part:

public List<List<Vector2>> levelPoints = new List<List<Vector2>>{};

First of all it does not show in the inspector (which might be the default behaviour for lists into lists, idk)
Secondly, this part doesn't seems to save for some reason...
I add things to it like that:

levelData.levelPoints[level-1] = path.points; //path.points is List<Vector2>
fickle mango
solid magnet
#

Ok thanks

solid magnet
#

Sorry I'm still new to this lol

#

That throws me an error, cannot converts from LevelPoints.levelPoints to Vector2

#

AAh those errors come from the script saving them

#

But now it does show up in the inspector

#

Still trying to find how to access the values

#

Now how to add things

#

I figured it out

#

I don't know if it fixed my problem

#

But at least now it shows up in the inspector

#

Thanks a lot

#

It fixed it

#

Tysm

steel snow
#

im trying to update normals after editing vertices but i am getting this error:

System.IndexOutOfRangeException: ReadWriteBuffers are restricted to only read & write the element at the job index. You can use double buffering strategies to avoid race conditions due to reading & writing in parallel to the same elements from a job.
This Exception was thrown from a job compiled with Burst, which has limited exception support.

not sure why though, this is the setup:

var vertHandle = new Deform(vertexData, uvs, output, spline, span, scale).Schedule(output.Length, output.Length / 8);

var tris32 = meshData.GetIndexData<int>().AsReadOnly();
var normalHandle = new RecalculateNormals32Bit(output.AsReadOnly(), tris32, normals).Schedule(tris32.Length / 3, tris32.Length / 8, vertHandle);

wondering if passing in output.AsReadOnly() is the issue? though i don't see why because recalc of normals depends on the completion of the vert handle so it should be fine...

#

ah i have fixed it nevermind πŸ™‚

worldly pecan
# worldly pecan Hey guys, I have a C# question; I have a list of structures, which I want to au...

Ok, after a lot of brainstorming I came up with this solution. We can expose the functions that’s originally defined by the interface by using a function pointer. Then we can define a struct that holds these exposed functions as well as the original pointer which can be put in a native array and used in a job.

To address mallocing enough space for the data we can define a function that queries the size of the object. When we create a new object we need to assign the function pointers to the specific functions defined by the specific structs.

Is this the best way to do this? Probably notβ€”tell me what you guys think though.

compact ingot
#

I don't think following pointers in jobs makes a lot of sense (performance/safety wise).

worldly pecan
long ivy
#

Out of curiosity, what are you actually trying to do goal-wise? I would shoot this down in a PR so fast

worldly pecan
#

I'm trying to do a bunch of calculations for some agents(mainly pathfinding) in a Unity parallel job where the each execution thread(?) handles an individual entity

#

There's also other considerations about storage and disposal cause I'm doing this for a procedural world

scenic forge
worldly pecan
scenic forge
#

That's already a performance loss

worldly pecan
scenic forge
#

No, well, not exactly

#

Usually your data are packed into a continuous region of memory, and when you schedule a job to run in parallel it has a batch count, so each thread processes batch count amount of work rather than 1 at a time.

#

It means that a thread when finishes one piece of work, the next piece's data is right there in the CPU cache and no miss.

worldly pecan
# scenic forge Usually your data are packed into a continuous region of memory, and when you sc...

I understand that--but if each job is a lot of work, the main concern is the cache misses inside a long job rather than between the next one. I plan for each job to do a lot of work, and the cache miss between processing the next entity is far less of a concern than the cache miss inside a single job.

What I mean is that if you have a job that processes 10,000 jobs, and each one takes 0.01 ms to complete, cache misses between them matter a lot, but if you have 100 jobs that take 1 ms each/thread cache misses between them matter less than they do inside it

#

Also I don't plan to put a lot of memory in these entities either

scenic forge
#

I'm not sure that's quite true, your IntPtr obj will be all over the place in memory, so every work which needs to dereference that, will be an almost guaranteed cache miss.

worldly pecan
compact ingot
#

what is happening in that long work unit?

worldly pecan
scenic forge
#

Sure I guess, but yeah you have just effectively reinvented dynamic dispatch with a vtable and a pointer to the object.

compact ingot
#

and the data of the graph fits into one memory page?

worldly pecan
#

I'll worry about cache misses with the graph later

compact ingot
#

you should worry only about them because it sounds like those are your bottleneck

worldly pecan
tired dome
#

hello all, how do i make this code function properly? i want to make an airship hover in place, and this code works fine if angular drag is set to some arbitrarily high number, but when i set it to 1 the airship flips out and starts spinning weirdly

private void ApplyFloatingPower()
{
Vector3 centerOfMass = rb.centerOfMass;
float upwardForce = -rb.velocity.y; // Invert the velocity vector to cancel out the vertical velocity
rb.AddForceAtPosition(new Vector3(rb.velocity.x, upwardForce, rb.velocity.y), centerOfMass, ForceMode.VelocityChange); // Apply the force as a velocity change

    // Calculate the current up direction of the object
    Vector3 currentUp = transform.up;

    // Calculate the desired up direction (Vector3.up)
    Vector3 desiredUp = Vector3.up;

    // Calculate the rotation required to align currentUp with desiredUp
    Quaternion targetRotation = Quaternion.FromToRotation(currentUp, desiredUp) * rb.rotation;

    // Smoothly interpolate towards the target rotation
    rb.rotation = Quaternion.Slerp(rb.rotation, targetRotation, 1 * Time.deltaTime);

    // Apply damping to the angular velocity to reduce oscillations
    rb.angularVelocity *= (1f - 1 * Time.deltaTime);
}
flint sage
#

Looks like ai

tired dome
#

? ah i did run this through chatgpt a few times, but each iteration it spit out just made things worse lol

flint sage
#

Also use proper code blocks

#

Some bits are missing

flint sage
#

Man this code is becoming more cursed the more I looked at it

tired dome
#

yeah sorry, physics is not my forte

upbeat path
untold moth
warm karma
#

Hi. Does anyone know if is it even possible to create an attribute that makes it so when the method is called, it automatically adds that method's name to a list? Like for example something like this:

public class RandomClass
{
    [Replayable]
    public void DoSomething()
    {
      //whatever
    }
}

And when I do RandomClass(), as it has the [Replayable] attribute, it should automatically call like another method. Is that possible?

compact ingot
warm karma
#

hmmmmm okay. I think I could do something like that. Thanks

steel snow
#

any one here know the algorithm to calculate normals for a mesh ?

#

ive tried two methods and it doesn't produce the same as unity's built in one i have no idea which algorithm they are using but their solution works

compact ingot
steel snow
#

is this unity's ?

compact ingot
#

No

steel snow
#

ah whats the bet it uses the same one i already use

compact ingot
#

there are many ways to calculate normals

steel snow
#

yup i tried 2 of them

#

both were not ideal

compact ingot
#

Look at that library

steel snow
#

yet unity's worked exactly how i needed it but their code is closed off

compact ingot
#

It has them all

steel snow
#

i only see one in their code?

compact ingot
#

unity probably is a cross-product average of all incident vertex edges or an interpolation of face normals calculated from triangle edge cross product

steel snow
#

the two i tried was sum the cross products for each vertex then normalize on the next pass, and the other was sum the normal * half length of the normal magnitude and then normalize those

#

the issue was edge vertices produced wrong normals

#

since they only join to half as many faces

#

This is the only normals calc i can see in that geometry project

regal olive
compact ingot
steel snow
#

are you sure thats what unity does though ?

#

this is what i originally did:

for (int i = 0; i < _triangles.Length; i += 3)
{
    int a = _triangles[i];
    int b = _triangles[i + 1];
    int c = _triangles[i + 2];

    var side1 = _vertices[b] - _vertices[a];
    var side2 = _vertices[c] - _vertices[a];
    var normal = math.normalize(math.cross(side1, side2));

    float area = 0.5f * math.length(normal);

    _normals[a] += normal * area;
    _normals[b] += normal * area;
    _normals[c] += normal * area;
}

then i normalize all the normals on the next pass

#

but it produced different normals to unity's

compact ingot
worldly pecan
#

Also that is how unity should be calculating normals(idk about multiplying by area)

steel snow
compact ingot
steel snow
#

but i have a theory for why mine is not correct

#

need to run some tests

worldly pecan
steel snow
#

yes they have different adjoining faces

compact ingot
royal moth
#

hey, i'm also trying to figure out how to give a sprite thickness, don't listen to people saying "well use a mesh duhh" because in the game they don't use meshes, it's part of the game's shader, i have NO CLUE how they managed to achieve it but it's probably something to do with parallax shaders, if you figured out how to do this please tell me i'm also trying my best to replicate this effect

#

i MANAGED to replicate it (poorly) on blender, but i have no clue how to do it on unity

steel snow
#

@compact ingotdont suppose you know how they recalculated the mesh tangents too?

compact ingot
steel snow
#

ive got no idea on that algorithm

compact ingot
steel snow
#

hmm that does not seem easy

compact ingot
#

(this is c++)

steel snow
#

thanks!

compact ingot
steel snow
#

neat, once this is done i finally got all the mesh generation applied to job system

royal moth
compact ingot
#

it doesn't mean its rendered like a regular normal map. Its just input for the custom shader that adds the shadows & highlights

#

actually it looks like it could also just be a bump + occlusion map, and the normals for the highlights are calculated from the bump

#

anyway, light edges on sprites are typically done with normal maps, the shadows could be something entirely separate (a post effect), assuming these are skeleton animated?

royal moth
#

okay i see, i'm less than a beginner on shaders and complex stuff like this, so i kinda get what you mean but there are a lot of stuff that i still don't understand, and i wouldn't know how to replicate it on unity

compact ingot
torn basalt
#

Maybe this is the wrong place to ask but does anyone know if it is possible to create a dotween sequence and run it in editor mode? I am woring on an aniumation tool and was curious about testing animations in Edit Mode

native beacon
#

Another option would be to use a geometry shader to just draw more planes for each sprite, to provide edge depth

frozen ravine
#

how do I retrieve these values via scripting?

#

I tried this, but it's giving me way more values than I expected. I want to just return the 3 AnimationCurves

wide mulch
#

Can I serialize and select between delegate functions in editor?

lethal oxide
lucid crane
#

Well, UnityEvents at least

frozen ravine
#

I was just asking how to get the animation curve from an animation clip

wide mulch
lucid crane
wide mulch
#

A dictionary lookup doesn't make sense, I could just use the enum values to index an array

lucid crane
#

Or if you want items blank. Though ig it depends on context and preference.

lethal oxide
#

does anyone know what "=>" is doing here?: (Grid<GridObject> g, int x, int y) => new GridObject(g, x, y). I thought it was related to lambda function but i am not so sure anymore. It looks more like just declaring and initializing a new GridObject

lucid crane
#

Or just single line methofs

#

int AddOne(int x) => x + 1;

lethal oxide
#

so AddOne is a method that takes input x and returns x+1 right?

#

thanks! I think i understand

sick flame
#

Hey folks, could you mention a scenario, when using fp16 provides visual artifact/degradation compared to fp32?

brisk pasture
#

anytime you have very very large objects or objects very far away from the worlds origin point

#

floating point numbers are just approximations, the larger the number gets the more precision is lost in that approximation

frozen ravine
#

all I want to do is get the 3 curves from the animation

#

but the function is returning 723 items in the array of curves for some reason

#

I assume it has to do with how curve bindings work, but I'm not sure what to do with the data since I can't find any documentation online about it

#

why does a curve binding give me an entirely new AnimatorCurve? How does it go from 3 curves in the animation to 723 bindings and how do I use those to get back to 3 curves?

#

do I have to combine them somehow?

wide mulch
#

With floats, when you go twice as far away, you get half the resolution

#

So since 32 bit floats have much higher precision than 16 bit floats, you'll have better resolution throughout

fickle mango
#

I have a build error:
MyScript, No suitable method found to override: OnValidate()
That script inherits from LayoutGroup and is inside an Assembly. I added a reference to UnityEngine.UI, but that didn't fix the problem.

untold moth
#

Remove the override keyword and it should work probably

fickle mango
#

nah, it is. The compiler doesn't give me an error, only when I try to build does it show up.

#

ah I found the problem:

swift shadow
#

What is making him do this?! Red arrow is where I press a button which changes a single integer, which should then be simply updated to GPU? I ain't even rendering here man

sly grove
#

Oh it's rendering

#

Time for the frame debugger

swift shadow
#

here is the CPU view

untold moth
brisk pasture
#

would get the frame debugger out

sick flame
#

Ok I got it πŸ˜ƒ

viral sage
#

This missing reference is eating my head, Basically this only comes sometimes, if i add some debug or something in the code and run again its not coming, also in the build its not happening, only in the editor its happening, Is there any fix for this or has any one faced this before? please help.

Error:
MissingReferenceException: The object of type 'UI_References' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
UnityEngine.MonoBehaviour.StopCoroutine (UnityEngine.Coroutine routine) (at <2d8783c7af0442318483a199a473c55b>:0)
UI_References.SetLoadingScreen (System.Boolean status, System.String msg) (at Assets/UI_References.cs:111)
LoginManager.Init (System.Boolean isTestUser) (at Assets/LoginManager.cs:102)
GameConfigurationManager.ApplyRemoteSettings (Unity.Services.RemoteConfig.ConfigResponse configResponse) (at Assets/UI Manager/GameConfigurationManager.cs:101)
Unity.Services.RemoteConfig.ConfigManagerImpl.HandleConfigResponse (System.String configType, Unity.Services.RemoteConfig.ConfigResponse configResponse) (at ./Library/PackageCache/com.unity.remote-config-runtime@4.0.2/Runtime/ConfigManagerImpl.cs:553)
Unity.Services.RemoteConfig.ConfigManagerImpl+<>cDisplayClass46_0.<DoRequest>b0 (UnityEngine.AsyncOperation op) (at ./Library/PackageCache/com.unity.remote-config-runtime@4.0.2/Runtime/ConfigManagerImpl.cs:542)
UnityEngine.AsyncOperation.InvokeCompletionEvent () (at <2d8783c7af0442318483a199a473c55b>:0)

tired fog
#

Scriptable Objects professionas, how can I check if an asset has been saved/is being saved? I'm losing some data on a material after an event to save is triggered. This is because Im setting some compute buffers into a material in the scene, and after the event of saving the data gets cleared, so I need to reset it. I would like to subscribe to an event to know if an aset has been saved and reload the textures if thats the case

tired fog
#

But this one is only for before

#

I need for after it has been saved, to reload the data, since after being saved, material data that doesn't have a property gets flushed (like compute buffers)

#

I found some issues online but sadly they are all unavailable to be seen in unity forums

amber moth
#

Hello guys,
is there any option for UIToolkit EnumField's Dropdown Position from code

obsidian glade
tranquil terrace
#

hey guys. I'm writing my own custom collision detection system using SAT. I'm trying to find collision points and I'm struggling to do so here. it works fine in some cases but not in others, it seems. seems to mostly bung up in vertical edges . any idea what might be happening?

sly grove
#

so I'm sure this is a special case in the code somehow

tranquil terrace
#

it seems to only be an issue with the vertical edges

sly grove
tranquil terrace
tranquil terrace
#

hey heres the code if u wanna have a look

dusty wigeon
#

Why are you not able to find the issue ?

tranquil terrace
#

so i'm struigglign

dusty wigeon
#

Because simply reading code is most of the time not enough.

#

Did you isolate your issue ?

#

Did you profile your code ?

#

If you are saying that your issue with vertical edge, have you printed what is the result of the expected collision.

#

Are you aware of what is a debugger ?

tranquil terrace
lethal oxide
#

let's say I have a class Player which uses interface IAttackable. I then do the following: IAttackable attackable = new Player(); . What would be the benefit of initializing this?

sly grove
#

The benefit of the interface is that you could have a piece of code that works with IAttackable. That one piece of code can work with a Player or any other type that implements IAttackable. So you don't have to write a bunch of different code that does the same thing

#

e.g.

public void DealDamage(IAttackable target, float damage) {
  target.TakeDamage(damage);
}``` as a quick dirty example
lethal oxide
#

so am I specifying the interface of player there?

sly grove
#

wdym? No you're not "specifying the interface" of anything

#
IAttackable attackable = new Player();```
This code just declares a variable and assigns it to a new instance of the Player class
#

nothing else
It does illustrate how a variable of the interface type can accept a value of a class that implements the interface though

upbeat path
sly grove
#

creating an instance of the Player class

lethal oxide
#

thank you both! Sorry, I am not up to speed on the lingo. Appreciate the patience

north osprey
#

Hey guys I'm making a SO that's capable of generating new cards for my game but I have one issue, I need to be able to know when the AssetDatabase has refreshed and unity has compiled my new generated code so then and only then I can generate the new SO from that newly created class. The code I'm sending here is still creating the new card with the BaseSO class for testing purposes, but I've already caught on that this issue is gonna happen. Any tips?


    private void GenerateScriptableObject()
    {
        //Find the correct class to inherit from
        
        //Create the ScriptableObject
        BaseCardSO card = ScriptableObject.CreateInstance<BaseCardSO>();
        AssetDatabase.CreateAsset(card, _cardSOPath + _cardName + ".asset");
        
        card.Name = _cardName;
        card.Description = _cardDescription;
        card.DeckType = _deckType;
        card.Image = _cardImage;
        
        //Clear the fields
        _cardName = "";
        _cardDescription = "";
        _deckType = default;
        _cardImage = null;
    }
    
    private void GenerateScript()
    {
        //Class name is going to be the same as the card name, prefixed with "XXX_" where XXX is the deck type
        var className = GetDeckTypePrefix() + _cardName;
        
        //We make sure there are no spaces in the class name and if we remove them and make the next character uppercase, we also remove special characters other than the underscore
        className = CreateValidClassName(className);
        
        //Create the Script
        string script = "Boilerplate Code here..."
        System.IO.File.WriteAllText(_cardScriptPath + className + ".cs", script);
        
        //After creating the script, we need to refresh the asset database so Unity can recognize the new script
        AssetDatabase.Refresh();
    }
}

compact ingot
north osprey
north osprey
#

Yup in regards to getting the new type I create, can anyone spot something? I can guarantee that both the namespace and assembly def of BaseCardSO and the dynamicly created types are the same:

private string CreateScriptBoilerplate(string className, string cardName)
    {
        return "using System;\nusing UnityEngine;\n"+"namespace Assets.Project._Scripts.SOArchitechture.Cards{ \n" +
               "\n[CreateAssetMenu(fileName = \"" + cardName + "\", menuName = \"Cards/" + cardName + "\")]\n" +
               "[Serializable]\npublic class " + className + " : BaseCardSO\n{\n    " +
               "public override void ActivateCard()\n    {\n        base.ActivateCard();\n        Debug.Log(\"Activating Card: " + cardName + "\");\n    }\n    " +
               "public override void DeactivateCard()\n    {\n        base.DeactivateCard();\n        Debug.Log(\"Deactivating Card: " + cardName + "\");\n" + "  }\n " +
               "protected override void OnEnable()\n    {\n        Debug.Log(\"Created script of type: \" + GetType() + \" in assembly: \" + GetType().Assembly.GetName().Name);\n" + "   }\n}\n} ";
    }

private void GenerateScriptableObject()
    {
        //Fully qualified name of the class
        var namespaceName = typeof(BaseCardSO).Namespace;
        var assemblyName = typeof(BaseCardSO).AssemblyQualifiedName;
        var className = _newClassName;
        
        string fullyQualifiedName = namespaceName + "." + className + ", " + assemblyName;
        Debug.Log(fullyQualifiedName);
            
        Type newCardType = Type.GetType(fullyQualifiedName);

        if (newCardType == null)  //<--- Always null 
        {
            Debug.LogError("Could not find the class " + _newClassName + " to create the ScriptableObject"); 
            return;
        }
(...)

serene jetty
#

would it be faster to calculate a triangle normal in a compute shader or on the cpu when creating the mesh?

clever urchin
#

How big is your mesh?

#

How are you making your mesh, how big is the CPU<->GPU overhead?

#

etc

serene jetty
#

just wondering cause if i do the normal calculation on the cpu im transferring less memory and the struct im using will fit evenly on the gpu cahce

rancid oxide
#

WebGL topic but its more on the technical side:
In my browser game I do API calls to an external service, for that I use an api key that is stored as an const string in the code.
I imagine that it is possible to somehow extract that key for malevolent use.
What can I do to avoid that?

upbeat path
rancid oxide
#

(idk if that is the right term but I guess they could track every message that comes in and out)

upbeat path
rancid oxide
clever urchin
#

I don't think it'll be too hard to test both with your setup, but mesh normal calculations are generally pretty fast anyways

scenic forge
#

Whatever external service you are using, there's a very good chance that it was not designed to be used directly on the client side (but rather intended to be used in your own backend). This means that very likely:

  • The service does not have fine grained access control. Getting access to the API key will allow someone to do anything the key can do, eg if the service is a storage layer and you are only using it to update player scores, yet someone getting access to the key can modify not just their own score, but someone else's score, or even delete someone else's account.
  • The service does not have any logging for you to know what people are doing with that key.
  • The service does not have any rate limiting and someone can spam certain endpoints to bankrupt you.
    With your own backend and you expose for example only a submit score endpoint, that's the only thing client can do, and you can properly protect that endpoint with authentication/logging/rate limiting.
rancid oxide
#

This service let me get text to speech audio, an it comes via a unity web request directly in form of an AudioClip

#

I image that in your way I should send the request from the side backend and then somehow transmit the output to unity

scenic forge
#

Is that service designed to be used in client directly?

#

Their documentation should be very clear about that. If the service is designed to be used in client directly, their docs will say so very clearly; if the docs mentions anything about the API key being a secret and should not be exposed, then the service is not designed to be use directly in client.

rancid oxide
scenic forge
#

Hmm not sure, I don't use it and from a quick scan of the docs nowhere it says whether your API key is sensitive or not, and the examples they show use keys client side, which seems to suggest your key isn't sensitive.
On the other hand, a quick Google search shows people who have their ElevenLabs API key compromised and used (Rabbit R1 being one of them which I found hilarious). When in doubt ask their support about your security concerns.

floral marten
#

is there a way to temporarily disable scene view mesh/object outlines? (ideally without force-changing users' currently set "show mesh outline" setting, this is for a plugin!)

tranquil terrace
tranquil terrace
jaunty swallow
#

Anyone know why having a NavMeshAgent on my object, rotates its transform by -90 on X axis?

#

I think it has something to do with me using NavMeshPlus, it probably tries to rotate the object to fit the navmesh which rotates to accomodate XY

sage radish
# floral marten is there a way to temporarily disable scene view mesh/object outlines? (ideally ...

This looks like the relevant editor code:
https://github.com/Unity-Technologies/UnityCsReference/blob/77b37cd9f002e27b45be07d6e3667ee53985ec82/Editor/Mono/SceneView/SceneView.cs#L2286C43-L2286C63
Based on this, only AnnotationUtility.showSelectionOutline (internal) determines whether selected objects have outlines, and it's the same property that gets changed by the Gizmo GUI.
I think the only way you can avoid changing that property is using something like Harmony (https://github.com/pardeike/Harmony) to hook into SceneView and modify it.

floral marten
#

hmmmm good point, but also, there is the s_CachedParentRenderersForOutlining and s_CachedChildRenderersForOutlining arrays in there catThink

#

but alas they seem to be populated on each call pensivebread

sage radish
#

Only if s_SelectionCacheDirty is true, right?

floral marten
#

hm, true

#

..this seems cursed

#

a true, "I could, but, should I?" situation

#

maybe it's fine to just, reflection edit the user scene view setting tired just feels kinda cursed

sage radish
#

If clearing the array with Reflection works, I would consider that less cursed, at least user facing. The user would be able to see the setting has been changed if they check the GUI, and try to change it.

floral marten
#

assuming it's not got some cursed dirtying patterns yeah

#

ill try it catnod

sage radish
#

I hope there's no assert checking if the input array is empty πŸ˜”

#

Otherwise you might need to give it a bogus renderer off screen.

floral marten
#

hmmm my reflection isn't finding the field

#

oh boy okay might be a version difference

#

yeah, I'm on 2022 LTS

#

field isn't there

#

looks like on 2022 LTS I want s_CachedParentRenderersFromSelection

#

oh no it works

#

it shows up for one editor frame, and then disappears

#

same thing during assembly reloads

#

but yeah it seems to work otherwise!

floral marten
#

@sage radish behold

public static class SceneViewHacks {
    // theoretically should work from Unity 2022.1 to 6000.0 (I only tested in 2022.3)
    #if UNITY_2023_3_OR_NEWER
    const string FIELD_PARENTS = "s_CachedParentRenderersForOutlining";
    const string FIELD_CHILDREN = "s_CachedChildRenderersForOutlining";
    #elif UNITY_2022_2_OR_NEWER
    const string FIELD_PARENTS = "s_CachedParentRenderersFromSelection";
    const string FIELD_CHILDREN = "s_CachedChildRenderersFromSelection";
    #elif UNITY_2022_1_OR_NEWER
    const string FIELD_PARENTS = "m_CachedParentRenderersFromSelection";
    const string FIELD_CHILDREN = "m_CachedChildRenderersFromSelection";
    #endif
    const BindingFlags bfs = BindingFlags.Static | BindingFlags.NonPublic;
    static readonly FieldInfo sceneOutlineParents = typeof(SceneView).GetField( FIELD_PARENTS, bfs );
    static readonly FieldInfo sceneOutlineChildren = typeof(SceneView).GetField( FIELD_CHILDREN, bfs );

    /// <summary>Hides selection outlines until a new selection is made,
    /// bypassing the user scene view setting</summary>
    public static void HideSelectionOutlinesTemporarily() {
        #if !UNITY_2022_1_OR_NEWER
            throw new NotImplementedException( $"Outline hiding not implemented for unity {Application.unityVersion}" );
        #endif
        sceneOutlineParents.SetValue( null, new int[] {} );
        sceneOutlineChildren.SetValue( null, new int[] {} );
        SceneView.RepaintAll();
    }
}```
jaunty swallow
#

Any ideas why it's firing the complete opposite way?

#

top transform is the red cube, bottom is the selected object

#
var raycast = Physics2D.Raycast(transform.position, Hero.Instance.transform.position, 9999, 10);

if(raycast.collider != null && raycast.collider.gameObject == Hero.Instance.gameObject)
#

the collider is always null

#

even if I walk into the raycast, it is still null despite the selected object having a collider and being on the right layer

hushed fable
# rancid oxide Then can't them spoof the communication between the server and unity?

You should assume any API you expose will be used by a thirdparty, and consider the potential abuse that could happen.
Wrapping an API is not the perfect solution, but it's way better than exposing your direct API key access to a thirdparty service. Having requests go through your server allows you to serve these requests within the context of your project, like you know a single client (IP, user) can't reasonably be doing thousands of requests per second.

south ibex
#

Is there any guides on implementing IK for articulation bodies? I'm in the process of trying to create physics-based procedural animation.

#

Attempting to use any physics-independent IK solver (I've tried unity animation rigging (with animator set to animate physics) and multiple github repos) doesn't seem to work

long ivy
worldly pecan
final steeple
#

Do you have a tl;dr on what Burst function pointers solve here? To my knowledge they are just a workaround for not being able to store delegates in jobs, but you could always store actual C# function pointers (+ some state like a GCHandle if you had an instance to invoke on)

worldly pecan
final steeple
#

You can store a managed function pointer delegate

#

i.e. delegate*<int, void>

worldly pecan
#

No you can't-- delegate* is a managed type

final steeple
#

It's not

worldly pecan
#

I tried--

final steeple
#

If Burst considers it one, that's a bug in Burst

worldly pecan
#

I tried storing it as delegate* unmanaged<void*, void>

#

it doesn't allow it to be stored

final steeple
#

Yeah this is a Burst bug, thanks Unity

#

You can cast it at the usage site just fine though

#
[BurstCompile(CompileSynchronously = true)]
public unsafe struct FunctionPointerJob : IJob
{
    [NativeDisableUnsafePtrRestriction]
    public void* Callback;

    public readonly void Execute()
    {
        ((delegate*<int, void>)Callback)(10);
    }
}

//

static void LogNumber(int value) => Debug.Log(value);

new FunctionPointerJob
{
    Callback = (delegate*<int, void>)&LogNumber
}.Schedule().Complete();```
#

this works fine

worldly pecan
final steeple
#

Function pointer types in C# are unmanaged, they're just addresses and not reference types
I guess Burst doesn't account for that in its validation code

#

Yeah they probably only check IsPointer and not IsFunctionPointer

#

You could probably report it and pray for it to get fixed lol

worldly pecan
final steeple
#

Burst FunctionPointers are specifically for managed delegates, not raw function pointers

#

i.e. public delegate void MyDelegate(int a);

worldly pecan
#

ah ok...

final steeple
#
public unsafe struct EntityFunction
{
    [NativeDisableUnsafePtrRestriction]
    private void* _pointer;

    public EntityFunction(delegate* unmanaged[Cdecl]<Entity*, void> pointer) => _pointer = pointer;

    public readonly delegate* unmanaged[Cdecl]<Entity*, void> Invoke => (delegate* unmanaged[Cdecl]<Entity*, void>)_pointer;
}
#

you could work around it with this for the time being

#

Burst should let you store that

#

Not ideal though, since you'd need a special struct for each unique function signature

worldly pecan
final steeple
#

There are quite a few niche attributes like that

#

Some of them have absolutely no documentation and I've never seen them used in any publicly available code

worldly pecan
final steeple
#

np!

sacred night
#

if I make a ScriptableObject instance through code (via the ScriptableObject.CreateInstance function) how does that behave at runtime? does it get saved to the disk with the rest of the game? I'm thinking about using SOs for save files

upbeat path
sacred night
#

oof. thanks

solar tangle
#

Hi,
Does anyone know how to programatically recenter the world origin(I dont mean to create a new gameobject and then assign everything under it, that would be local recentering). My idea is to recenter to a specified point so it would be recognized as new world origin. This would also help in the case of photon which sends networked data based on world origin(i suppose)

dusty wigeon
sly grove
solar tangle
#

yes we can do that but photon or anyother networking for the matter wont move the transforms based on that right? it would be local repositioning in that case.

solar tangle
# dusty wigeon The easiest would be to use HDRP feature "Camera Relative Rendering" https://doc...

yea recentering is one of the options iam exploring for my usecase, so basically i have a passthrough app which would allow users to place a fire-place in their environment and other users spawn around it(not -colocation). So my thought process is, since each user should be able to place a fireplace anywhere in their environment then it should kind of act like a starting point(aka new origin) and photon should spawn and move players relative to that origin?
Any other way do you think would be better?

dusty wigeon
#

Simply push the position and interpreted it the way you want on the other device.

#

Alternatively, you can simply put everything inside a "root"

#

Also, if you are not in the same physical space, you do not even need that.

solar tangle
#

i'm doing quest passthrough so people will scan the room and place the fireplace in their environment. What i'm confused about is when trying to sync player movements, photon will always sync movement in terms of world transform.
Even if i put everything inside a root, not sure photon will follow the hierarchy, it would still sync transform in world space

#

atleast thats what i think

dusty wigeon
#

The documentation of Photon state that it sync the local

#

You should head to their forums/social platform if you struggle with that.

solar tangle
#

Got it and Thanks! let me try exploring more on this.

south ibex
#

How can I get a point that's a specific radius away from another point?

Trying to make an enemy whose main mode of movement is rolling. I want it to roll within a specific distance to the player. I tried just moving the object towards the player and stop at a specific distance (using velocity on a rigidbody), but it always ended up getting too close and becoming stuck because it was moving towards the player, not towards a point that was a specific distance from the player.

devout hare
#

origin + direction * distance is a point that's distance away from origin if direction is a normalized direction vector

south ibex
#

πŸ‘ thanks

grand dagger
#

yo so i have this door scirpt, but the problem im having is that the door is coming of its hinges, does anyone know how to make it like stay on the hinges?

compact dawn
#

Im not sure if this is the right channel to ask this question, but I am helping develop a CAD software for a specific robotics program and we are in the process of adding chains that connect gears together. We are trying to have a system that works by clicking a button and then selecting two gears and a chain automatically generates around the two. Ive recently found a asset that helps alot with the generation of chains on a path and that is the "Splines". The problem im having is i dont know how to automatically generate the spline in the right place on the gears and im not sure if its even possible. I have a picture below of an example that i manually created the points for it to rotate around. To restate the question, how can i have this type of spline generate in a loop around any two gears that i select with the press of a button.

worldly pecan
#

If you need to do it in-game that's harder cause you probably need to build/import your own editor

dusty wigeon
# compact dawn Im not sure if this is the right channel to ask this question, but I am helping ...

You will not be able to rotate the chain around the object from a transform given that the shape is not circular.
You have multiple alternative you could look into that I can think at the moment:

  • Using skinned mesh
  • Dividing in small section each individual piece of the chain and animating that
  • Dividing in two part. Circular and linear.
  • Using shader to displace the chain

(In theory, you only have to make a small movement loopable movement to be able to rotate)

frozen imp
#

@halcyon cloak No collab posts here

halcyon cloak
#

If there a channel for that

normal lagoon
#

I have been thinking and want to understand how to properly build the logic with Zenject. I may have MonoBehaviour components, but I think it's not just about using two interfaces and "cluttering" the container with dependencies that always need to be injected into MonoBehaviour through a custom constructor method.In general, I am thinking of starting to create objects from prefabs at the moment of initialization/dynamically. Here, I don't fully understand the correct approach. Yes, there should be a service that handles configuration delivery, and a factory (here, I don't want to use a Placeholder because I think it will require a lot of injections and writing code, which isn't a problem).Suppose I have a player who will have scripts like PlayerSpawnPoint, IPlayer, PlayerProxy (can it be used to hide the implementation? Here, too, I don't understand if it's necessary to use an interface for the factory and proxy implementation - I think not). Some kind of PlayerBehaviour and so on will also be needed, and everything should be covered by a facade.It's interesting to create the player at the level of GameObjectContext, that is, through PlayerInstaller or not.
My main problem is that I don't fully see the application architecture. Of course, many implementations are possible, but I want to finally try dynamically creating objects, attaching components, using an asset provider, and developing smoothly. I sincerely ask for advice, as I'm still far from being a Unity expert.

compact ingot
# normal lagoon I have been thinking and want to understand how to properly build the logic with...

Zenject only makes sense for very large teams for long lived live services. It’s a terrible burden on your process if you are a small team and people on the team don’t fully grok automated dependency injection. Zenject does allow you to do all sorts of stupid hacks and does in no way guarantee a sustainable architecture. Mind also that DI containers are really bad at handling dynamic scopes. The pattern is at its best when all factories and scopes can be defined statically on startup.

normal lagoon
compact ingot
#

Don’t use DI containers in unity would be my advice

normal lagoon
#

how to learn if... :))

half swan
compact ingot
#

if you must use one, use VContainer

normal lagoon
#

Well, they don't differ much as far as I know when it comes to proper dependency injection, just smaller memory allocation. Am I wrong?

half swan
compact ingot
#

proper Unity architecture cannot be learned by reading, you need to shoot yourself in the foot 1000 times to actually learn what works and what all the theory you read about means.

compact ingot
#

I bet you everyone who works in a zenject project that’s older than a year hates life

#

it’s one of those techs, that once an org adopts them, it gets taken hostage and starts an unhealthy dependence on it, unable to move past it, despite all the health hazards, stuck.

#

jira being another example

sage radish
compact ingot
compact ingot
sage radish
# compact ingot So you probably mostly used it as a fancy service locator?

Mostly. We use the subcontainer scopes a bunch (project > scene > game object), to easily get references between scripts under the same game object hierarchy. We also use Convention Based Bindings a lot: Container.Bind<IFoo>().To(x => x.AllNonAbstractClasses().DerivingFrom<IFoo>()), to implement some things by just defining a new class.

For example, we have a simple save data system that uses that. If you want to save some data somewhere, all you have to do is define a class:

public class LevelSaveData : SaveData
{
    public int LevelsUnlocked;
}

and inject it where ever you want to access it:

[Inject]
private LevelSaveData _levelSaveData;

private void OnLevelComplete()
{
    _levelSaveData.LevelsUnlocked++;
}

A save manager class injects all the SaveData and manages the serialization and deserialization.

#

Not sure if a service locator will allow these sorts of use cases. Or if VContainer has something similar.

compact ingot
#

The average dev will just [inject] what they need an never stop for a second to think about the message flow & coupling or where stuff should be routed, whether a new system is needed to handle a case etc. So you end up with ravioli connected by invisible spaghetti and many bugs that were once discovered by static code analysis become runtime bugs.

sage radish
compact ingot
#

i'm currently trying to find an architecture/patterns where juniors feel empowered to contribute at a systems level

dusty wigeon
wide mulch
#

How can I interpolate an object that isn't a RigidBody or a CharacterController

sly grove
#

generally "interpolation" just means "move a little bit each frame until you reach your destination"

#

It's also not really an advanced question

wide mulch
#

So I'm writing a custom thing for movement because RigidBodies and CharacterControllers don't have what I want, and right now I'm manually changing transform.position of the object in FixedUpdate, but I have a camera set to follow the player, and that uses LateUpdate, and there's a lot of jitter because of it

#

If you want I can put the script I made in a pastebin

sly grove
#

if the object is moving in FixedUpdate there will always be jitter unless you do your own interpolation, yeah

wide mulch
#

Alright

#

I was just curious if unity had a generalized solution already

sly grove
#

I mean generally if you're not using physics, you would just move your object in Update

wide mulch
wide mulch
#

I got interpolation working :3

#

I'm storing the old and new positions, as well as the current Time.time, and then using the amount elapsed since that to lerp between the old and new positions

fickle mango
#

Is there a way to have async methods as listeners for UnityEvents? If I make my method async I can no longer select it in the inspector, and the way it is right now it doesn't work sometimes:

compact ingot
sly grove
compact ingot
#

async event handlers are however a somewhat problematic idea producing all sorts of race conditons and overall debugging hell (thats already bad due to (unity)-event usage)

scenic forge
#

It's probably one telling you to do _ = UpdatePlayerName(input); for clarity.

south ibex
#

Trying to write a behaviour tree using muse. I want enemy to move towards player if enemy is within a distance of 20 units but do something else if the enemy is outside of that distance.

Currently, the "Move the Rigidbody" action (custom) will cause it to stay in the true branch even if it becomes false because the action is always running.

#

I tried adding an "Abort if" node but it caused the "Move the Rigidbody" to never run

#

This is how I had that setup

#

I also tried without the inverter just to make sure

lucid crane
#

Seems pretty simple:
if (playerDistance > 20)
{
moveToPlayer();
}
else
{
// Do something else.
}

south ibex
#

it's not a script, it's a behaviour tree.

lucid crane
austere jewel
surreal crane
#

Is there a way to reset an AnimatorControllerPlayable through code just like how an Animator behaves when the GameObject it's attached to gets deactivated and reactivated again (restart from entry node)?

round blade
#

Good morning / afternoon/ evening depending on where you are from!

I am looking for some pointers in the right direction on how to set an external display (display 2 for simplicity) and be able to change it's resolution at runtime. I already have a list of resolutions that I can set but when I change the resolution from the dropdown only display 1 is responding and changing:

https://pastebin.com/meGHcB9G

Any settings I'm overlooking for the additional displays?
launch arguments etc

real blaze
#

hi. anyone knows why the _qrcodeImage 's image isn't being updated in the UIToolkit?
its populated by _qrcodeImage = this.Q<Image>("qrcode-image");
and in the debugger I can see the image property is fully set.

#

for the record, this works in the webgl build, but not in the editor

#

do I have to call a specific function to force-update it?

#

can I view the texture in the uitoolkit debugger? to ensure it's not being hidden by an overlay

upbeat path
real blaze
#

is there really no way to debug the image at runtime?

#

(also for the record, the arcode is a valid link and I tested it in other qrcode makers, it works. so the issue here is regarding UITK, not the qr-code)

upbeat path
# real blaze didn't work

Looking at my UITK Image code, I do not use the image variable. I create a Sprite from the texture and set the sprite variable

real blaze
#

i'll try that in a editable package

#

alright, MarkDirtyRepaint didn't work.

#

so, apparently its the qr-code generator. sorry for the misslead

#

so, right, the qr code generator was compressing the texture, and I don't know why but this was messing it up, probably because of my compression settings (ASTC)

#

or rather, this was the author's issue. according to here the compression must occur after applying textures

sly grove
lofty solstice
#

Anyone here familiar with the CullingGroup API? I'm having trouble understanding how it works based on the Unity documentation for it.

steel snow
#

im a bit lost on the difference between these functions:
Graphics.RenderMesh which says RenderMesh submits the Mesh for rendering, which means it does not render the Mesh immediately. Unity renders the Mesh as part of normal rendering process. If you want to render a mesh immediately, use Graphics.DrawMeshNow.

why / when would you want to opt to draw immediately? Also how does the render mesh function differ to Graphics.DrawMesh

sage radish
# steel snow im a bit lost on the difference between these functions: `Graphics.RenderMesh` w...

If you want to render meshes to be drawn by cameras in the scene, you should use the non-immediate methods. These can be called from any point during the frame, such as Update, as it will just get queued and rendered later.

But if I want to render a mesh immediately, such as when performing your own rendering without using Unity cameras, you need to use immediate methods like Graphics.DrawMeshNow or those found in CommandBuffer.

steel snow
#

not sure why you would want to render without using a camera? also why is there a Draw and a Render mesh function being non immediate

#

how does unity differentiate between Draw and Render

sage radish
#

The Draw methods are older, the Render meshes are newer. They both do the same things, just with slightly different parameters.

steel snow
#

ah okay

#

weird they have both but neither were marked deprecated

#

unnecessary confusion by unity πŸ˜„

sage radish
steel snow
#

ah i see

sage radish
#

But this is a very direct method of rendering, which bypasses Unity's lighting and other rendering systems.

steel snow
#

so like projecting to a billboard etc

#

so you dont have to use a second camera

dapper cave
#

I'd like to bounce ideas regarding speed vs code readability.
I have this AI checking for friends and foes in vicinity and was briefly tempted to do bitwise test for team check, but it seems that physics is so expensive anyway that i might keep the list.Contains.
teams are held in scriptable objects and team-wide affinity is a reference to other team SO, when team A attacks team C, team C SO gets updated and all of team C counter attack.
what do you guys think, by eperience.

tall ferry
sinful meadow
#

what methods can i use to make setpixels() and apply() faster on very large textures?

tropic vigil
round blade
marble bramble
#

I'm instantiating a GameObject from a prefab and GetComponent<>() returns null when trying to access any other script attached to the game object prefab. What gives?

tender flame
#

ive been having an issue for about 3 days asking in the #πŸ’»β”ƒcode-beginner channel and i am continously getting an issue saying that c# dev kit is targeting the wrong program format x86 instead of x64

#

thats the error code

flint sage
stoic otter
#

is there a limit as in how much things you can save to the appdata folder?
we have a game what only can crash when the appdata save folder is clean?

flint sage
#

As long as there's disk space

upbeat path
upbeat path
stoic otter
#

aa thx steve!

stoic otter
#

so i found a bug in my code where i subscribe 2 times on a event += in the on enable and on disable
the strange thing is the bug happens most of the time for the players who playing it the first time what happen when you 2 times subscribe += to a event

upbeat path
stoic otter
#

Yeah but cant it give you a memory leak

#

right

upbeat path
#

that is not a memory leak, they are completely different beasts

flint sage
#

If you never unsubscribe, those instances never get GC'd though

#

So technically if you do it a lot you might run out of memory

stoic otter
#

we got another one we dont get this one either

#

it crashed our entire game

flint sage
#

No idea what that sentence means

stoic otter
#

so i have this error how do you clear the profiller memory ?

lament salmon
timid grail
tender flame
pearl jackal
#

How do I get a shader to render on top of everything?

fallow echo
#

render it last, turn off depth testing for it, I guess πŸ€·β€β™‚οΈ

lucid crane
#

Is it a bad practice to store all logic about players in one class? I currently have two classes for each player: One being for the player state machine and one for the player physics. These classes are highly dependent on each other. What I was thinking is because they exchange data so much is to merge them into one class, but I fear that would defy conventions. If they were both in one class it would defy the β€œsingle use” convention of SOLID.

fallow echo
#

if both of them know about each other - that's not good, but if only one knows about the other - that's fine (usually)

lucid crane
fallow echo
#

this seems fine

#

is it annoying to work with for some reason?

#

if not, I'd probably leave it as is... if yes - then I'd try to resolve the annoyance in some way other than merging these

lucid crane
# fallow echo is it annoying to work with for some reason?

Kinda. Mainly because PlayerHandler has a parameter called CharacterData, which represents the character the player is playing as. Different characters have different collision boxes and falls speeds which are needed by the PlayerPhysics class. What I currently do is feed those variables to them and assign them as fields within the PlayerPhysics when PlayerHandler starts running.

fallow echo
#

mm... to be fair though - the S in SOLID is also overrated... I use an extended version of it called "less than five responsibilities principle" πŸ˜„

fallow echo
#

does that need to be part of the PlayerHandler in the first place?

lucid crane
fallow echo
#

I mean, from what I understand those are params needed by the PPhysics class... can't you just put them there and set them there?

#

although, injecting params is generally not unreasonable πŸ€·β€β™‚οΈ

lucid crane
fallow echo
#

yeah... well then just inject the physics part into the physics one as you do (it could be one struct with the data, so that you won't need to do multiple assignments and can add more data later on, etc.) πŸ€”

#

without seeing the code, it seems fine.. (am a bit lazy right now to read code and think hard though, but someone else might feel like it)

lucid crane
#

That way I don’t have to keep them as parameters. Though if you said merging is fine, I might just do that.

fallow echo
#

the separation sounds reasonable, tbh, so I'd prefer to keep it... but if you don't mind the potential issue that you may need to separate them again in the future, because something else needs to control the physics thing - then it's not the end of the world
usually it goes the other way around... you start with a merged thing (because it's simpler) until you have a reason to split it... technically split gives you more flexibility

steel snow
#

so im generating a mesh asset, i save it as a subasset to my scriptable object and i assigned it to the field in my scriptable object yet in the inspector i get type mismatch (see image)

the asset file is valid though... when i double click the type mismatch box it loads the mesh inspector and sure enough its correctly showing a mesh so why is it a type mismatch?

#

this is how im loading it to the field in OnValidate

var path = AssetDatabase.GetAssetPath(this);
var subAssets = AssetDatabase.LoadAllAssetRepresentationsAtPath(path);
foreach (var subAsset in subAssets)
{
    if (subAsset is Mesh mesh && mesh.name == "Plane Mesh")
    {
        _planeMesh = mesh;
        return;
    }
}
tender flame
#

I have found very little information on this specific issue related to vs code and unity. Whenever I launch vs code with the default console template opened it loads for a second and gives me this error. I know I have the latest version of the .NET SDK installed as x64 and I have no idea how to change what the c# dev kit is targeting. I have tried uninstalling the SDK, vs code, and all of the extensions within vs code. I have also tried editing my system environment variables and changing the path settings. I have truly no idea what to do and have been stuck on this issue for days. any help is much appreciated!

lucid crane
#

Get the unity vs code extension, then in your unity settings set you IDE to vs code

lethal oxide
#

My units are forgetting which healthSystem it has created an instance of during setup. Why is this occuring?

sage radish
lethal oxide
sage radish
lethal oxide
#

healthSystem is a class. A field is a variable stored on class

sage radish
lethal oxide
#

ah i see what you mean

#

i dont think its either of those issues then. Like you said, nothing should be able to set the field to null since its private. And the field is definitely assigned before Damage is called since the target units are in the scene from the very start and initializes healthSystem on Start()

sage radish
#

Or if the script is disabled, Start won't be called, but it can still be collided with and Damage can still be called on it.

tender flame
lucid crane
opal wigeon
#

If I perform some kind of function a few thousand times is it better if variables are declared outside of it?

float b; 
void A()
{
  b *= b;
}
#

I'm thinking that would free up the garbage collector as the function is reused

upbeat path
#

but it would be damn silly if b were a local variable

opal wigeon
upbeat path
dusty wigeon
#

Are you sure of that ? Pretty sure local variable are basically free and it might even be better given that they would be closer.

#

In any case, it would probably not even be perceptible

sly grove
sly grove
opal wigeon
sly grove
#

due to memory locality right on the stack

#

but - why don't you benchmark it?

opal wigeon
sly grove
opal wigeon
sly grove
honest hull
#

So in the unity play mode(not build), there isnt really a way to create a new screen dimension setting and set to it all from a C# script, right?

tropic vigil
honest hull
#

oooo this looks perfect!! thanks!!

tender flame
earnest geyser
#

does anybody know some resources that talk about procedurally animated spiders? I have a working procedurally animated spider but it gets messed up when i try to make it walk on surfaces with steep slopes.

I think I need to cast some horizontal rays to check for obstacles in front since I'm only casting downwards rays from above every foot but I'm not sure what to do

sly grove
#

Other than the fact that the body stays at the same height all the time. It would be a bit more realistic if the body adjusted according to the leg heights

earnest geyser
#

ok wait it's not steep enough

#

and when i rotate the body

sly grove
#

that's a problem

#

it will need to follow

#

Also "raycasting straight down" isn't going to cut it for a spider which can walk straight up vertical walls and even upside-down

earnest geyser
#

when i rotate the body and move it, legs at the back just go limp

#

instead of raycasting straight down

#

should i raycast down with respect to the body rotation

sly grove
#

definitely, something like that

earnest geyser
#

i think my rays are green

#

but it should be red

#

right

regal olive
#

Hello

#

What RenderParams should I use for Graphics.RenderPrimitives(rp, MeshTopology.Lines, (...))?

#

the example is for MeshTopology.Triangles

untold moth
regal olive
#

Well I have no triangles, just edges to draw

#

I'm searching for a way to draw a debug wireframe in ECS

#

given list of edges

slate sapphire
#

hey so i need help making a game, im struggling to put my ideas into it and need help, i know it kinda seems a little jumpy but i could really use the help.

regal olive
#

I may get the triangles but thought it's possible just with edge list

untold moth
regal olive
#

okay, thanks

untold moth
slate sapphire
#

good point, didnt see the other chats at first

lethal oxide
#

I have methods with default input values. i am using a delegate to use these methods but right now its giving me an error because there is nothing within the delegate parameter. How do I specify that the delegate should use default value?

sly grove
#

Not sure what you mean by default value

#

Show code?

lethal oxide
sly grove
#

Show your code if you want specifics

sage radish
#

You can do this:

public delegate void AttackAction(int damage = 15);

private void Invoke(AttackAction attackAction)
{
    attackAction(); // passes the default 15 damage.
}

But the default will always be 15. It doesn't matter what the defaults are for the actual method assigned to the delegate, or if there are any defaults at all.

lethal oxide
#

thank you both!

livid zephyr
#

Hey everyone! I'm trying to set up a flag football game where flag pulling is the base of the game. The offensive player has to avoid the defensive player and score while the defensive player has to pull the flag to win

#

The defensive player is controller by Ai and has a navmeshagent and also the football field has Navmesh

#

Currently the way i have it set up, the ai is supposed to go towards the offensive player to "pull its flag" but the ai stops each time i move my player and then moves once my player is stationary

#

Here's my code for the ai

#

Im using Unity and VS 2022

upbeat path
#

<@&502884371011731486> Spam

austere jewel
#

!warn 972587276972462171 don't spam random crap here. There is no off-topic.

thorn flintBOT
#

dynoSuccess jamafr has been warned.

sly grove
stray plinth
#

Did anyone make a weapons system with scriptableObjects, that hold both the game assets and the logic to spawn, fire them?

It’s probably a well used/represented solution, that is why I am wondering what caveats/issues/etc. were encountered?

livid zephyr
tropic vigil
dusty wigeon
tranquil terrace
#
if (IntersectCirclePolygon(closestPoint, radius, polygonVertices, out circlePolygonNormal,
                    out circlePolygonDepth))
            {
                if (circlePolygonDepth < depth)
                {
                    normal = circlePolygonNormal;
                    depth = circlePolygonDepth;
                    return true;
                }
            }
            if (IntersectCirclePolygon(capsuleA, radius, polygonVertices, out circlePolygonNormal,
                    out circlePolygonDepth))
            {
                if (circlePolygonDepth < depth)
                {
                    normal = circlePolygonNormal;
                    depth = circlePolygonDepth;
                    return true;
                }
            }
            if (IntersectCirclePolygon(capsuleB, radius, polygonVertices, out circlePolygonNormal,
                    out circlePolygonDepth))
            {
                if (circlePolygonDepth < depth)
                {
                    normal = circlePolygonNormal;
                    depth = circlePolygonDepth;
                    return true;
                }
            }
#

I've got an issue with my capsule. my current order is checking the closest point, then the top, then the bottom.
but sometimes the capsule will phase through walls. is my order wrong?

compact ingot
livid zephyr
sly grove
steel snow
#

does any one know how to update unity navmesh in runtime in specific areas i really don't understand the api at all and theres few example codes provided

#

i just want to update the navmesh after adding more meshes to the scene but its a bit complicated

steel snow
#

i cant use that

#

i need to rebake the navmesh in an area when i add more geometry to the scene - navmesh obstacle only allows two basic shapes which is totally useless

#

its not really obvious to me if when updating via the bounds it will wipe out the areas outside of the bounds or not so it becomes a bit unclear if im using the right thing

native beacon
#

Sounds easy to test though

steel snow
#

i did i tried this:

    private void OnEnable()
    {
        _collider = GetComponent<MeshCollider>();
        _worldBounds = _collider.bounds;

        var center = _surface.transform.TransformPoint(_worldBounds.center);
        _localBounds = new(_worldBounds.center, _worldBounds.size);

        var sources = new List<NavMeshBuildSource>();
        NavMeshBuilder.CollectSources(_worldBounds, NavMesh.AllAreas, _geometrySources, 0, new(0), sources);

        var handle = NavMeshBuilder.UpdateNavMeshDataAsync(_surface.navMeshData, _surface.GetBuildSettings(), sources, _worldBounds);
        handle.completed += OnComplete;
    }

    private void OnComplete(AsyncOperation operation)
    {
        if (operation.isDone)
            Debug.Log("NavMesh update completed successfully.");
        else
            Debug.LogError("NavMesh update failed.");
    }
#

but this does not do what you would think it does

#

this is the visual of the navmesh + the bounds area i want to update

#

but when i run it i get this:

#

makes no sense to me

long ivy
#

MeshCollider bounds are already worldspace so your TransformPoint line makes no sense

#

you want the inverse if you want center to be in _surface's local space

steel snow
#

i finally got it working

#

i can now use abstrast polygon shapes as navmesh obstacles

#

took forever to figure it out

sand shore
# tranquil terrace I've got an issue with my capsule. my current order is checking the closest poin...

checking the capsule's endpoints firs and then the closest point might give you better results because endpoints are often more critical for collision detection. also instead of returning early when collision is detected have you tried to loop over all the points you need to check for collisions and then gather the results and keep track of the smallest penetration depth so you can then return whether any collsion was detected along with the best normal and depth values.

solid grove
#

I must be misunderstanding how RenderTextures work. I'm trying to render two different textures, one that goes to the screen, the other to be used for a graphical effect. I created a secondary camera + render texture and set the target buffers of said camera to the rendertexture, I then set a texture in my compute shader to the render texture. After the the scene renders, when I then read the data of each pixel out to a dummy array just to verify what data is in it, all the values are blank (they should not be). When I open the frame debugger, I can confirm that rendering of the scene is occurring, but it doesn't seem to be writing to the RenderTexture. I feel like I must be missing some fundamental step, anybody know?

#

In the frame debugger, the steps that draw the secondary texture state the target buffer as a temp buffer, but I don't know if that's unusual.

lament sphinx
#

Whats wrong. I have a camera and will calculate the right upper point dinstance from pivot. With the height all is okay but width is wrong

lucid crane
#

2x/2 = x

#

(2 * x * y) / 2 = xy

sly grove
#

is this a perspective camera or orthographic?

lament sphinx
#

its a perspective

sly grove
#

So are you calculating an angle here?

#

or what

lament sphinx
#

i try to calculate the half distance from the cameraposition vector to the roght or left end of the view

sly grove
#

so what do you mean by distance

#

also for a perspective camera distance between parts of the camera view depends also on the depth that you're looking at

lament sphinx
#

the calculation what i postet works in 2d. i dev it for thois . but now i convert to 3d and there this doesnt work with this formular

sly grove
#

Yeah because it makes so sense, you're dealing with angles here

#

you can't treat an angle as a position

#

So you have to specify the problem better

sly grove
#

for this you should use Plane.Raycast

lament sphinx
sly grove
#

e.g.

Plane p = new Plane(Vector3.up, Vector3.zero); // assuming your plane is flat and at y = 0

Ray r = Camera.main.ViewportPointToRay(new (0, 0));
p.Raycast(r, out float distance);
Vector3 topLeft = r.GetPoint(distance);

r = r = Camera.main.ViewportPointToRay(new (1, 1));
p.Raycast(r, out float distance);
Vector3 bottomRight = r.GetPoint(distance);
lament sphinx
#

camera viewport and from the pivot to the corner the distance

sly grove
#

that point can be 0 units from the camera or a million units from the camera

#

and it represents a different position in space depending on where

#

My example code projects that point to a given Plane in the game world and uses that.

#

but it depends what you actually want.

lament sphinx
#

okay i try it

#

i think i must think other in 3d

sly grove
#

yes you have to change your thinking

wary blaze
#

From what I've read online, if Unity is using the Async Upload Pipeline, I should see specific Profile markers in the profiler (AsyncUploadManager.ScheduleAsyncRead, AsyncReadManager.ReadFile, and Async.DirectTextureLoadBegin). I'm assuming these markers will appear on the Main Thread in the CPU Profiler? Can anyone confirm?

frozen ravine
#

is there a way to rename these sub-assets?

#

whenever I try editting its name with .name and refreshing the asset list, I get errors in the console

upbeat path
# frozen ravine is there a way to rename these sub-assets?

what are we even looking at here? Those look like ScriptableObjeccts so F2 should be able to rename.
Also just saying ' I get errors in the console' is not very helpful. Show the errors
Also, not a code question, please use the correct channels

frozen ravine
#

well it is a code question because I'm trying to rename them with code

#

they are scriptable objects

#

but they're sub-assets

#

the type you create with this code

#

the error is that it basically loses a reference to the asset once I try renaming it, which doesn't happen with normal scriptableobjects, only the sub ones

#

I also tried using AssetDatabase.RenameAsset which isn't doing anything at all on the sub-asset

exotic trout
#

@frozen ravine complete shot in the dark but any chance the so's .name isn't matching it's file name? messed w/ making so's via code but not subasset stuff

frozen ravine
#

well it works with my other scriptable objects, it just doesn't work with that one

#

Unity's just weird about sub-assets, you can't even rename them in the inspector manually (which is why I'm trying to figure out how to do it with code)

upbeat path
frozen ravine
#

no, this is the project view

#

I can rename everything else just fine

#

as far as I know, in the project view, not being able to rename them is just an oversight, but I figured there would be a way to rename them via scripting

final steeple
#

If you click on the asset's name, wait half a second, and click again, does it let you rename it?

#

Unity is weird about exposing renaming

upbeat path
#

I suspect this may be a design flaw in Unity, probably related to meta data

final steeple
#

Certified Unity moment

frozen ravine
#

that really sucks lol, because the sub-assets are really good for organization

upbeat path
#

if you cannot f2 rename then that is actively blocked by code so the chances are you just cannot rename

frozen ravine
#

true

upbeat path
#

very odd behaviour, normally Unity does not care about names at all

jade veldt
#

There has to be a better way of doing this in ECS right? If so let me know, the goal is to make the workers do two seperate tasks repeately after each other. This "works" but seems like a slow way of doing so

#

also, is there a way to trigger code via an event / pruning rather than just boolean locking with ECS?

real blaze
# jade veldt also, is there a way to trigger code via an event / pruning rather than just boo...

if you're looking for an event, you won't find it (unless you give up on burst-compatibility for every code using that system/component). but you can make it easier for yourself by creating generalized data types that at least make it consistent across your application. example:

public struct Event<T> where T : unmanaged
{
    private T? _args;

    /// <summary>
    /// Gets the event arguments if the event is valid. Also consumes the event.
    /// </summary>
    /// <param name="args">Arguments of the event</param>
    /// <returns><c>true</c> if the event is valid.</returns>
    public bool TryGetArgs(out T? args)
    {
        args = _args;
        _args = null;
        return _args.HasValue;
    }

    public void Invoke(T args) => _args = args;
}

invoking the event:
spawner.spawnWorker.Invoke(...)
using the event (it also consumes it, but you get the idea. change it to accept IDs if you want proper subscription system in it) :

if (spawner.spawnWorker.TryGetArgs(out var args))
{
    // use args...
}
hollow fog
#

I watched Codeer’s video on how to make a procedural animation. I need a bit of help with the second step of the video, which involves anchoring the bottom of the leg to the ground.

azure meadow
#

I have a mysterious object that came from a wacky json object... most of the times I can convert it with:

(T)Convert.ChangeType(mysteriousObject, typeof(T), CultureInfo.InvariantCulture)

however, if the object is something that looks like a list, that fails.
my workarround is to reserialize it and parse it back in the correct type πŸ˜›

  string json = JsonConvert.SerializeObject(mysteriousObject);
  T value = JsonConvert.DeserializeObject<T>(json);

But this feels really hacky πŸ˜…
What is the correct C# syntax for this kind of crazy cast?
(note, just casting (T)mysteriousObject fails)

sly grove
azure meadow
#

the json is being parsed as Dictionary<string, Dictionary<string, object>> it's a two key deep json object that can have pretty much anything on the last level

#

the problem in question is an array of bool

sly grove
#

well.. that's why it's coming in as an object of course

azure meadow
#

does C# has something like void*?

#

πŸ€”

sly grove
#

object is the closest thing

#

I'm just curious why you feel you need it

sly grove
azure meadow
sly grove
#

Sounds like you're using Json.NET and JsonConvert. For a structure like this you could consider using the JObject API instead of JsonConvert

#

That will give you a lot more control here

#

but a lot of this depends heavily on where the JSON is coming from in the first place and why it has that format

#

there's probably a better/cleaner way with less ambiguity

hushed fable
#

There are settings to control the amount of type information, if that's the problem you are running into

azure meadow
#

I will investigate the JObject πŸ€”
The json should always come from another c# serializer... but I am not entirely sure πŸ˜…

sly grove
#

right assuming JsonConvert is being used to serialize in the first place. But JSON.Net's type information strategies don't all conform to the actual JSON standard πŸ˜‰

azure meadow
#

thanks a lot!!! JObject (and the entire family of J* thingies) worked perfectly and are WAY easier than typeguessing in a C# dictionary πŸ₯Ή

sly grove
#

If this wasn't Unity Json.NET also supports dynamic which would probably be good for your use case but Unity IL2CPP doesn't support it!

rancid bane
#

not sure if anybody can help but

#

please i cant build my apk without fixing

thin mesa
#

you're not even looking at the correct line

rancid bane
#

its the line it sends me to

#

its highlighted

#

Lemme check

crystal relic
#

The error says line 71

rancid bane
#

do i delete this

crystal relic
#

Send a snippet of a few lines before and a few lines after

rancid bane
#

before

crystal relic
#

Yeah delete what's on line 71.

rancid bane
#

ok let me see

#

not again...

#

now can u help fix this 😒