#archived-code-general

1 messages ยท Page 184 of 1

prime sinew
#

you said you want to be able to change what every item does

#

that's why i suggested an interface

#

do you know how to reference another script to call functions on it

thorn glade
#

yeah i do

prime sinew
#

okay

thorn glade
#

but i want it to be dynamic

prime sinew
#

that doesn't really mean anything

#

maybe look into events and delegates

thorn glade
#

to be able to call the same name of a method

prime sinew
#

what?

thorn glade
#

but the script is different

prime sinew
#

then use interfaces

#

if you dont know what an interface is, then look that up

thorn glade
#

its UI right?

prime sinew
#

no

#

look up C# interface

thorn glade
#

yeah this is it

#

thank you

#

i didnt know how to explain it

prime sinew
#

Should've looked it up before saying this

thorn glade
#

i thought its just UI

prime sinew
#

Glad it can help though

gray mural
#

is there an Abs method for vectors?

prime sinew
gray mural
prime sinew
#

I guess you can just Abs each float in it

gray mural
#

I see,

#

I will make an extension method then

#

thank you

quaint rock
#

confused what the usecase for wanting abs for vectors is

gray mural
coarse narwhal
#

Hey Folks, I have an arena game where there is a player controlled object, and things in the arena that you pickup by driving over them. Is it best to put the collision script on the player object, or the prefab of the pickup items?

loud oracle
#

https://gdl.space/iqupazacit.cs I'm trying to do a total war or like age of empire like movement, but I can't like even think of how to add diagnol line, so far all I can do is line my troops up horizontally, any ideas?

ocean river
#

ay

#

i want to check if the collider matches the collider component created by an script on incoming trigger collision

#

is it possible?

#

like not if the incoming collider matches or anything, but if the collider that reciever the collision is the same as an created collider component.

hexed pecan
ocean river
#

i mean with multiple collider components

#

i want to make an radius sensor script that i can assign and it works.

loud oracle
#

If you put the OnTriggerEvent method on your scanner it should run for every object it triggers I think, then in there you can individually check if that object is the one you want

ocean river
#

nah i mean

#

i added an component via script

#

assigned to an variable

#

now i want to check if that collider that was collided with matches that var

#

or maybe tellme how to create an child gameobject via code?

prime sinew
#

but why can't you just access the parameter passed by the trigger collision message and compare that to the variable

gray mural
#

is it possible to Attach to Unity using code?

#

I mean

if (Input.GetKeyDown(KeyCode.Space))
    StartDebugging();
swift falcon
#

hello wise UDC, I come to you at a time of great need
I'm trying to figure out what would be the most optimal way to keep track of millions of different points on different bits of map geometry
the naiive answer would be to use particles, but research seems to show that Unity's particles are on the CPU and I'd be limited to ~50k
I'm looking into if shaders could potentially be more powerful but if anyone has suggestions / ideas I'd be extremely interested

leaden ice
#

You're talking about particles and shaders so maybe you're asking how to render something?

#

What are you trying to do?

swift falcon
# leaden ice What are you trying to do?

Experimenting with a system where a sound will create a bunch of raycasts onto nearby geometry, and the points on nearby geometry that each ray hits have a glowing particle spawned there that lingers

heady iris
#

This does kind of sound like a situation for gpu particles

#

you can shovel a very large number of world-space points into gpu memory

#

i was playing with a particle demo a friend made that did a million without too much trouble (purely gpu-simulated)

swift falcon
#

That's what I concluded from researching the topic, and I'm starting to re-learn shaders

#

A million would be ideal

heady iris
#

i wonder if you could use the visual effect system

swift falcon
#

I found some easy solutions to it using HDRP, but I wanted to see if it was possible with URP

#

Would this be screen space shaders?

heady iris
#

not really, since these are world-space points

leaden ice
#

do you need to interact with these things?

heady iris
#

to be honest I'm still a little mystified by a lot of the VFX Graph system

swift falcon
# heady iris What'd you do there?

I found a video of someone replicating a LiDAR effect, and I could def modify it for my purposes. It used the HDRP visual effect graph

heady iris
#

the documentation is all over the place

swift falcon
swift falcon
heady iris
#

as in, positions in the world :p

#

that's all

#

X-space means "in the coordinate system of X"

swift falcon
#

oh,

#

I was under the impression shaders like

#

affected objects

#

as in they affect the shading of the faces of objects

#

didn't know that you could just go anywhere in the world

heady iris
#

That's true for mesh renderers.

#

and I presume that even things like particles have some similarities

#

e.g. by slapping lots of quads all over the place

#

screen space shaders, for example, just draw a single big quad over your entire screen

swift falcon
#

hmm,

#

so is a 'World-space shader' a thing?

heady iris
#

I don't have a lot of experience with the more esoteric shaders, like what the Visual Effect system might use

earnest gyro
#

Is there an easier way to set a GameObject to be a specific "type" of object other than Tags or a script with an Enum? I prefer the Enum route, but it feels a little excessive to attach a script to an object just so I can specify an Enum type.

heady iris
earnest gyro
#

I want to just add an Enum component. lol

#

Ok

heady iris
#

Remove the Start and Update methods and they won't get called by unity

#

('cos they won't exist)

earnest gyro
#

Makes sense

heady iris
#

the "enabled" checkbox should disappear from the component in the inspector

earnest gyro
#

So they're practically weightless then?

#

In terms of runtime?

heady iris
#

(very confusing)

swift falcon
#

<-- confused ourplea

heady iris
#

I guess the ideal "dot shader" would just have a huge list of vectors

#

for each one it'd make up a quad that's pointing at the viewer and render it

#

note that I am just guessing wildly here. i really need to learn this stuff myself...

swift falcon
#

ty! will ask

brittle haven
#
[System.Serializable]
public class Level
{
    public string LevelName;
    public List<BlockData> Objects;
}
[System.Serializable]
public class BlockData
{
    public int BlockNumber, BlockType;
    public float BlockX, BlockY, BlockZ, BlockValue, BlockValue2;
}
#

thislevel is Level
How can I make an "if" statement that checks if only x, y and z floats exist in the Objects inside thislevel

steady moat
#

Such as -1 or float.MinValue

rigid island
#

^^ value type always exists

steady moat
#

You could also use NAN I think

heady iris
#

what would it mean for a level to have an object without a position?

brittle haven
#

There are 3 floats. their names are x, y and z

heady iris
#

those values not existing doesn't seem reasonable. i wonder if there's a design issue here.

steady moat
#

Probably like the size of the level

rigid island
#

hmm maybe you can use nullable floats

steady moat
#

Terrible idea

#

Nullable with Unity Serialization

#

Wack

rigid island
#

true, forget what i said lol

heady iris
#

The player is able to possess any Entity in my game. Each Entity has a Brain. AI Brains are separate from player Brains.

Until now, I've only had one kind of player Brain. So, I just had a single PlayerBrain that was attached to whichever Entity was being possessed by the player at the moment.

However, each Entity has a specific player Brain that makes sense for it. Humanoids need the HumanoidPlayerBrain. Spectators just need a SpectatorBrain.

How should the Entity indicate which kind of Brain it wants? I see two options:

  • Every Entity has its own instance of a playable Brain. That makes for lots of duplication, but I guess I can just prefab each kind of Brain.
  • There is only one of each kind of Brain, all attached to a singleton. Entities need to be able to tell me which Brain they want.
#

The latter one feels better to me, but I remember this exact topic coming up yesterday

#

you can't really serialize a component type

#

I guess I can just have an enum.

#

Not the worst thing in the world.

#

It's a reasonably small set of Brain types.

#

okay, yes, that answers my own question ๐Ÿฆ†

mystic ferry
#

does FindObjectOfType<T>() search for all additively loaded scenes, or only the active scene?

heady iris
#

I guess I could construct a new Brain each time one is needed, too, yeah.

#

some Brains need special configuration (e.g. providing references to specific features of an Entity)

steady moat
#

If you do not need anystate in your brain, then use SO.

heady iris
steady moat
heady iris
#

well, there are two situations where that can happen

#

1: the player possesses them

#

2: some kind of effect replaces their Brain

#

like, imagine a "berserk" effect that just throws all of their AI out and makes them punch whoever's closest

#

That's actually working very well right now.

steady moat
#

Seem to me that it is kinda complicated. Just modulate the behavior.

heady iris
#

I suppose. I'll feel it out as I start adding some more content.

steady moat
#

For the issue of reference, you would need to have a component that hold the reference for you.

#

And at that point, I wonder if you should just include the brain in the enemy directly.

#

And just swap whenever it is needed

heady iris
#

yeah, that was option #1. very simple.

#

today's relatable screenshot.

steady moat
#

In our game, we have BehaviorGraph that are instantiated SO. The data is hold on the Entity itself. I guess that would be more inline with the Factory approach

heady iris
#

yeah.

#

the critical thing is that literally any of these solutions is wildly better than my old code

#

where every kind of entity had its own bespoke class and had separate blobs of code for player and non-player control

#

the enemy class was 2,200 lines long.

#

after pulling a lot of stuff out into a state machine

steady moat
#

Oh... that is nothing

heady iris
#

i'm sure you've seen worse :p

#

actually, only the original player class even let you control it

#

i thought about adding enemy control for a minute and then decided it's time for an overhaul

#

the player character behaved very differently when AI-controlled, since it let a NavMeshAgent set its position instead of using a rigidbody

#

notably, it would just...go through obstacles

steady moat
#

I have the equivalent of 10k lines for the player through inheritance.

heady iris
#

implementing everything twice was not fun

steady moat
#

6k lines for the share behavior between a player and an enemy

rigid island
brittle haven
steady moat
#

Terrible nightmare

heady iris
mystic ferry
#

I was just about to test it so you saved me some time

heady iris
#

the documentation could really be more specific

rigid island
heady iris
#

it seems somewhat difficult to work with multiple scenes in general

mystic ferry
#

lots of teams seem to be using a multiscene workflow these days

rigid island
#

yeah sadly, but there are ways. What do you need to do exactly?

mystic ferry
#

instantiating some UI prefabs at runtime and using a game manager to sanity check all loaded scenes to make sure it doesn't exist anywhere else

rigid island
#

not need to go searchin

mystic ferry
#

that'll work actually, should be a lot faster than a bfs search lol

harsh bobcat
#

is a HashSet<myInterface> or generally HashSet<myClass a bad approach? I'm assuming it uses the reference to the object for the hashcode and not the data

harsh bobcat
#

like if the objects data completely changes that shouldnt affect the objects hashcode or the HashSet itself right

steady moat
#

Not the data

harsh bobcat
#

nice thanks

#

how much memory does a reference tend to take up?

steady moat
harsh bobcat
#

I'm wondering if its any worse to have a hashset of references vs a hashset of other data

mystic ferry
#

well references are pointers so almost nothing

#

don't take this the wrong way but you sound like you're optimizing something that doesn't need optimizing

steady moat
#

That would be 64bit on 64 processor 32 on 32 bit processor

harsh bobcat
#

I was just wondering if that was a bad choice but it seems pretty fine

#

the problem is the set will have counts in the 10-100k range in theory

#

so if I used lists and tried to compare two of them that could get slow

steady moat
rigid island
mystic ferry
heady iris
#

you'll want to listen for the scene-loaded events

rigid island
#

so it ran in the bg while the second debug.log ran first

#

    IEnumerator Start()
    {
        DontDestroyOnLoad(gameObject);
        Debug.Log(FindObjectsOfType<Tee>().Length);
        SceneManager.LoadScene("scene2", LoadSceneMode.Additive);
        yield return new WaitForSeconds(2);
        Debug.Log(FindObjectsOfType<Tee>().Length);
    }```
civic palm
#

Trying to build for Linux, but clang seems to be against this idea

#

No less than four different error messages

#

All rather substantial

rigid island
# mystic ferry god I love nondeterministic engines

sorry so yeah using Async no need for delays ๐Ÿ˜›
nice to know it scans all loaded scenes, TIL

IEnumerator Start()
  {
      DontDestroyOnLoad(gameObject);
      Debug.Log(FindObjectsOfType<Tee>().Length);
      yield return SceneManager.LoadSceneAsync("scene2", LoadSceneMode.Additive);
      Debug.Log(FindObjectsOfType<Tee>().Length);
  }```
mystic ferry
rigid island
heady iris
#

specifically when you're writing "async" methods

#

i put that in air quotes 'cause it's going to be a unity coroutine

#

but close enough

#

in an async method, you're allowed to just wait for another async thing to complete

rigid island
#

yeah bootleg async

heady iris
#

since you won't block the main thread

rigid island
#

i use true async when i do maui stuff

heady iris
#

this does lead to a "turtles all the way down" problem

#

where calling async methods can only happen from async methods

#

fortunately, here, you just pitch it in a coroutine and call it a day

rigid island
#

blessed be JOBS

heady iris
#

i used jobs to do gradient-ascent for an RTS AI

#

nice and fast

#

i feel like i could batch up a bunch of these queries into some kind of horrific compute shader

#

maybe

rigid island
#

Im trying to go full ecs but it gets complex quick for me

heady iris
#

i've made one tech demo in (mostly) full ecs

#

way too complicated: making a sort of LOD system that would show a city in the distance

#

then show blocks, then buildings, then individual people, as you got closer

rigid island
#

the next cities skyline ? :p

spring creek
heady iris
#

This was right at the 1.0 release

#

actually, it might have been just before...

#

I remember following a tutorial that is no longer in the DOTS GitHub repo

#

lemme find that

#

Ah, here we are

#

I learned from this.

#

well, the "tanks" tutorial is still there; it's just formatted a lot differently now

#

it doesn't have as much verbosity in it

#

I think this was back when the official documentation was still very...sparse

swift falcon
#

As a pure hypothetical would it be smarter to perhaps create a decal or something instead of trying to use this godawful vfx graph

#

It does not feel like it was designed for this

valid minnow
#

ok so i need some help with something, imagine i had a box and on each point of the box and i have a dot in the center, when the top left box point is equal to one, the dot moves there, if the top left and bottom right are eqaul to one, it finds the average and puts the dot there, kinda like how a joystick works, if you dont understand i can ellaborate but i need help writing code for this, heres an image for reference.

#

basicaly when the mad value = 1 dot will be on bottom right, when it eqauls 0 dot will be in center

#

but the same for every corner point, and if more than 1 are equal to one, it finds the average

simple egret
heady iris
#

hmm, I was going to say to give each emotion a coordinate and just add their (weighted) values

#

but that'd make the dot fly off the screen if you were mad and uh...tired?

simple egret
#

Can be an option, 2 numbers ranging from -1 to 1, one per axis

heady iris
#

I guess you could take the weighted average

#

Yeah. that'll work.

#

0.5 mad, 0.3 happy, 0.2 sad:

(0.5 * [1, -1] + 0.3 * [-1, -1] + 0.2 * [-1, 1])

                  0.5 + 0.3 + 0.2
#

with a special case for having no emotions at all

shell scarab
#

or just use a Vector2 and transform the dot locally around an empty game object at the center

ember cape
#

Should my Camera, Audio Listener and Event Listener be marked as DontDestroyOnLoad() so I can have a single instance of each? Because right now I had one for each scene and am getting this in the console:

There are 2 audio listeners in the scene. Please ensure there is always exactly one audio listener in the scene.
There are 2 event systems in the scene. Please ensure there is always exactly one event system in the scene

heady iris
#

are you additively loading scenes here?

ember cape
#

Yes I am

heady iris
#

Then you'll either need to make sure only one scene contains those components, or you'll want to DDOL them, yes.

somber nacelle
#

that should be "and you'll want to DDOL them", no? because DDOL doesn't inherently prevent more than one of the same object, in fact it would just compound the issue as scenes are loaded and unloaded

heady iris
#

I guess it depends on what's happening here

#

If it's one "main" scene with several other scenes you add and remove, then I'd just leave the camera in the main one

#

but if there isn't one main scene, then yeah, they should just live in that DontDestroyOnLoad scene

#

and even if you are doing the former, that strategy still works just fine

ember cape
#

So if I decided to keep my main scene, with my Camera, Audio Listener, Event Listener and my different controllers.
And decided to load other scenes additively, marking them as DDOL would be useless?
And of course the different objects in the main scene would not be present in the other scenes and I'd have to figure out a way to get these objects from the main scene to my other scene after loading is complete.

#

Am I getting this right?

somber nacelle
#

if you never unload that main scene, then yeah its pointless to mark those objects as DDOL. but if you additively load scenes and unload that "main" scene at some point but still plan to additively load those other scenes then yeah, you'd want those objects to be DDOL so they aren't destroyed when everything else in the main scene is

north cobalt
#

This is the video showing the game main mechanic character 1 (angel) move to the door, Then replay (the same moves that player gave to the game (inputs) ), Now the player play as the character 2 (devil) trying to kill the character 1 (angel)

kindred cairn
#

Hey guys, hi, i'm looking for someone that can help with my code, its about steering behaviors, i'm trying doing my enemy AI script, basically avoid an obstacle, but im getting little stucked on it

#
    {
        Vector2 intention = Vector2.zero;
        obstaclestocollide = 
            Physics2D.OverlapCircleAll(transform.position, radiusDetecObstacle, layerMask);
        if (obstaclestocollide != null)
        {
            foreach (Collider2D obstacles in obstaclestocollide)
            {
                Vector2 directiontoObstacle
                    = obstacles.ClosestPoint(transform.position) - (Vector2)transform.position;
                float distanceToObstacle = directiontoObstacle.magnitude;
                float evadeForce = radiusDetecObstacle - distanceToObstacle / radiusDetecObstacle;
                directiontoObstacle.Normalize();
                
                rivalAIRB2D.velocity = rivalAISpeed * Time.deltaTime * directiontoObstacle * evadeForce;
            }
        }
       
    }```]
heady iris
#

you have not described what your problem is or what you have tried doing

kindred cairn
#

just a second, i was drawing

#

the problem is, im not soo good with Vectors and stuffs

#

basically i don't how to calculate the trajectory

#

put it in code

#

like in the print a have the idea, but how to put it in action, i really can't see it

hexed coral
#

Your code for setting velocity is likely incorrect, Delta time doesn't make sense there.

Delta time is used for immediate moving, not setting speed

heady iris
#

yes -- multiplying by deltaTime tells you how far you'd move in one frame

kindred cairn
heady iris
#

you should!

kindred cairn
#

its a 2d game

heady iris
#

velocity is how far you move per second

#

that's what the rigidbody expects

#

if you set the velocity to how far you'd move in one frame, then that's like dividing your velocity by the framerate

#

at 100 FPS, deltaTime is 0.01

kindred cairn
heady iris
#

i wouldn't say it "applies the framerate"

#

it will behave correctly.

hexed coral
#

If it's a vehicle you should consider using smoothlerp instead of abrupt changes in velocity

heady iris
#

if the velocity is Vector2.right, the rigidbody will move to the right at 1 m/s

hexed coral
heady iris
#

indeed

kindred cairn
hexed coral
#

Wait

#

Why aren't you using navmesh

kindred cairn
heady iris
#

I guess it is going to be correct, instead of wrong

#

Set the velocity to how quickly the rigidbody should be moving

kindred cairn
#

right

hexed coral
kindred cairn
#

okay

hexed coral
kindred cairn
#

i really like the ideia, but im trying to implement my own codes, cuz i want design a lot of behaviors to my enemys

#

to bring life to it

hexed coral
#

You put your code on top of a existing navmesh framework

#

Navmesh will merely help you calculate those directions

#

Nothing stops you from "bringing life" to it

heady iris
#

yeah, you can prevent the NavMeshAgent from actually moving

#

and then just ask it how it wants to move

kindred cairn
#

i know, but i really apreciate code all this thing, but of course, if i get tired, i'll give up, and go to navmesh

shell scarab
# kindred cairn i know, but i really apreciate code all this thing, but of course, if i get tire...

i understand wanting to do it from scratch. It's very helpful in learning too. However what you're asking for help on is not a very easy task if you're doing it from scratch. What you may be able to do is get the vector from the enemy to the player, then raycast along that and if it hits something start rotating that vector left or right (probably both at once) and when it stops hitting something move in that direction, but keep trying to rotate it back towards the player.

#

although that alone could get stuck in areas pretty easily

hexed coral
#

You're basically going to have to code your own navmesh them, otherwise your agents will likely get stuck at many different situations, consider searching about a step by step process of coding a navmesh framework

kindred cairn
#

"you may be able to do is get the vector from the enemy to the player, then raycast along that and if it hits something start rotating" how

#

?

shell scarab
#

you could combine the A* algorithm with this vector idea and basically eliminate the directions that lead to dead ends.

kindred cairn
#

like avoid = obstacledirection - enemypos;

shell scarab
#

if you're having a hard time understanding the vector math required, perhaps it's time to read up on it or use navmesh:
https://www.youtube.com/watch?v=MOYiVLEnhrw

Welcome to my four part lecture on essential math for game developers ๐Ÿ’– I hope you'll find this useful in your game dev journey!

This course will have assignments throughout, if you want to maximize your learning, I recommend doing them!

If you are enjoying this series, please consider supporting me on Patreon!
๐Ÿงก https://www.patreon.com/acegik...

โ–ถ Play video
kindred cairn
shell scarab
#

you can also rotate vectors using quaternions but that's a whole other mess, but luckily unity has some things like Quaternion.AngleAxis to help.

kindred cairn
#

i came here just to know how to make a simple line of code, but now i see i was lazy

kindred cairn
#

thanks to all

shell scarab
#

yea, pathfinding is a pretty big thing. However if your game is simple enough you can probably just say start moving at 45 degrees when there's an obstacle in front

#

for example if it was a sidescroller with an enemy chasing you or something, then that would possibly work

stark sun
hexed coral
#

You didn't assign "EnemyMovement" anywhere, it should even be throwing a null reference exception

#

In fact almost everyline there can throw an exception

#

This will return null if no component was found
other.gameObject.GetComponent<EnemyMovement>()

valid minnow
heady iris
#

seems valid to me

#

just watch out for division by zero

valid minnow
heady iris
#

(you could prevent this by adding a tiny constant term to the denominator)

#

or by just having a special case

shell scarab
#

I still think it's easier to just move the dot relative to a transform at the middle of the scale with a vector2

chrome spoke
#

Hey, I'm sure this is a really simple question, but how do I reference a C# script in another script. I am making a card game and I want a Card class to be referenced and used in a manager scripts. The only way I have found to do that online is to grab the reference from an object, but I don't have the script attached to objects; instead, want to use the class itself within another script. How can I do this?

robust dome
#

ideally, you just declare the name of the Class and reference via inspector

#

[SerializeField] YourClassname yourClassname; << assign via inspector per drag drop

then use it inside of your script with
yourClassname.someVariable

leaden ice
#

Also is your class that you want to reference a Monobehaviour or not?

chrome spoke
#

No it's not a monobehaviour

leaden ice
#

Do you want it serialized in the inspector?

#

If not you can just make an instance with new

#

Like a normal C# class

chrome spoke
leaden ice
#

The using things at the top are just convenience so you don't have to write the whole fully qualified name of the class

#

They don't do anything besides that

#

E.g. you can write GameObject instead of the full name which is UnityEngine.GameObject

green drift
#

How do i reference the TextMeshPro text type in a script? I was following a tutorial for a game, but they use just "Text" objects and not "Text- TextMeshPro" , then they declare some variables to drag and drop said items in the editor.

public Text currentHealthText;

But when i went to do that, i cannot drag and drop them into the editor?, my guess is that it has to do with the type Text being different than the actual game Objects i'm using, so, how do i set the type correctly?

green drift
#

Ty

#

Now it says that it cannot be found

#

Do i have to import something?

vagrant blade
#

You need to use the TMPro namespace, yeah

valid minnow
#

i try to average them out but it makes the dot go off screen

hexed coral
valid minnow
#

actually i have an idea, ill just set the Y or X value of the dot equal to the perimitor of the box if it goes outside of it

shell scarab
shell scarab
# valid minnow

since you posted a screenshot it's hard for me to read it and type at the same time

#

but u can use a Vector2 to tell it up/down/left/right by setting the x/y component of the vector to a value between -1 and 1 for both, then you can multiply both the x and y by half the length of the square.

valid minnow
shell scarab
#

what?

valid minnow
valid minnow
shell scarab
#

to get half the length of your square multiply the x or y size by the scale then divide by 2

valid minnow
#

actually its kinda hard to understand, could you send code lol?

#

if not ill figure it out ig

shell scarab
#

which part is hard to understand? I know I did not explain it very thouroughly.

valid minnow
shell scarab
#

so your vector2 has an x and y component. the x and y component will be each individually expect a value of -1 to 1, -1 being all the way left/down and 1 being all the way right/up.

valid minnow
#

cause how it works rn, is i have floats for each corner that change depending on the value, and then i add them together and find the average then thats the position of the dot, but that makes it fly out of the sqaure if more than 1 of the floats is more than 0

shell scarab
#

you would then multiply that vector by half the size of your square, and set the gameobject's local position to that value.

valid minnow
valid minnow
shell scarab
shell scarab
valid minnow
valid minnow
shell scarab
#

do you have some way to track how happy/sad/afraid/mad something is?

valid minnow
#

thats kinda already what i have, but im just averaging the numbers instead

shell scarab
#

make a variable for happy/sad that is a float, and limit it to a range of [-1, 1].
then make a variable for mad/afraid and limit it to a range of [-1, 1].

valid minnow
#

hold on

#

how do i send code again?

shell scarab
valid minnow
#

k

shell scarab
#

you probably want to use Vector2.Lerp here.

This is very untested, I'm literally writing it in discord, it could be something like this:

float happySad = 0; // value is from 0 to 1
float madScare = 0; // value is from 0 to 1

Vector2 position = Vector2.zero;

Vector2 first = Vector2.Lerp(new Vector2 (-1,1), new Vector2(1, -1), Mathf.Clamp01(happySad));
Vector2 second = Vector2.Lerp(new Vector2(-1, -1), new Vector2(1, 1), Mathf.Clamp01(madScare))

position = (first + second) / 2;
valid minnow
#

thats my current code

shell scarab
#

dude there's a clamp function lmao

valid minnow
valid minnow
shell scarab
#

Mathf.Clamp(numberToClamp, min, max);

valid minnow
#

what does it do

shell scarab
#

it clamps the number to or between the min and max

valid minnow
#

ohhhhh

shell scarab
#

if less than min, it returns the min number. if more than max, returns the max number. otherwise, return the number supplied.

valid minnow
#

yeahhh thats a lot easier

shell scarab
valid minnow
# shell scarab is there a reason?

cause there gonna be there own functions in the game im working on, and eventually im gonna replace these floats with statics or something

shell scarab
#

but here:

float happy = 0; // value is from 0 to 1
float sad = 0;
float mad = 0; // value is from 0 to 1
float scared = 0;

Vector2 position = Vector2.zero;

Vector2 first = Vector2.Lerp(new Vector2 (-1,1), new Vector2(1, -1), Mathf.Clamp01((happy + sad) / 2));
Vector2 second = Vector2.Lerp(new Vector2(-1, -1), new Vector2(1, 1), Mathf.Clamp01((mad + scared) / 2))

position = (first + second) / 2;
valid minnow
#

lemme see if that works

shell scarab
#

yes because I don't have unity open

#

remember, set the dot's local position to the position value

#

and make sure its parented to the square or whatever has an origin point at the center

valid minnow
#

for some reason

#

it makes the dots positionX negative 1 when i play it

#

but it seems to work? maybe?

#

besides that

shell scarab
#

can u add a debug log statement to log what the local position is after setting it, and what first is, and what second is?

valid minnow
#

first vector is the local position, second is first, and third is second

#

weird.... ๐Ÿค”

#

any idea?..

shell scarab
#

all your happy/sad/mad/scared values are 0?

#

i know the problem is with the happy/sad/mad/scared values being seperated. Can you try it again with them being exclusive like originally stated? then default of 0.5 would be in the center.

#

pretty sure that would work, and it's more clear to have the emotions tied to one variable if they're eclusive.

valid minnow
shell scarab
valid minnow
shell scarab
#

make 2 variables instead of 4 you mean?

valid minnow
shell scarab
#

well once it works like that then figure out how to split it into 4

shell scarab
#

because they HAVE to be tied to each other regardless, so it makes sense for it to be like that. There's no way to have both 1 on happy and 1 on sad.

valid minnow
#

in the middle

shell scarab
#

ok try this then

valid minnow
#

really the dot needs to be closest to whichever value is higher but also pulled back by the other values

shell scarab
#

just a negative in front of happy and mad

valid minnow
#

ok

shell scarab
#

but then the problem is the lerp, don't do that actually

#

just try with the 2 variable thing. If it works, there, figure out how to split into 4

valid minnow
#

yeah it didnt work cause they had to be negative for it to move

valid minnow
#

its still -1 over on the x

shell scarab
#

with both values 0.5?

valid minnow
#

oh no

#

its centered with 0.5

shell scarab
#

yes

valid minnow
#

now how do i make that work in 4 directions tho

shell scarab
#

why doesn't it work in 4 directions now?

valid minnow
#

so why would it be differnt now if i added 2 more

shell scarab
#

so if you set one value to 0.25 and one to 0.6, what happens?

valid minnow
shell scarab
#

with the two setup

valid minnow
#

listen there has to be an easier way than thi

#

this

shell scarab
#

this is pretty easy

valid minnow
#

this just seems overly complicated

#

it worked fine with the 4 thing besides it being -1 over on the x

heady iris
#

You should do a weighted average of each emotion

valid minnow
heady iris
#

Assign each emotion a position. They will probably be [0,0] to [1,1] or [-1,-1] to [1,1]

valid minnow
heady iris
#

Multiply each position by its weight, then sum those up

#

Then divide by the sum of the weights

ruby nacelle
#

Hey! is there any way I can improve my dash? It's a little clunky

    void OnRoll(InputValue value)
    {
        // Input handling and movement
        if (!isAlive) { return; }
        if (!rb2d.IsTouchingLayers(LayerMask.GetMask("Ground"))) { return; }

        float moveInput = Input.GetAxis("Horizontal");  // Get input from the player

        if (Mathf.Abs(moveInput) > 0.1f)
        {
            if (_canRoll)
            {
                _isRolling = true;
                _canRoll = false;
                trailRenderer.emitting = true;
                animator.SetTrigger("Rolling");
                FlipSprite();
                StartCoroutine(StopRolling());
            }

            if (_isRolling)
            {
                rb2d.velocity = rollingDirection.normalized * _rollingVelocity;
                return;
            }

            if (cc2d_Body.IsTouchingLayers(LayerMask.GetMask("Ground")))
            {
                _canRoll = true;
            }
        }
    }

    private IEnumerator ResetRollingAnimation()
    {
        // Wait for a certain duration
        yield return new WaitForSeconds(0.5f); // Adjust the duration as needed

        // Reset the "Rolling" trigger to transition out of the animation
        animator.ResetTrigger("Rolling");
    }

    private IEnumerator StopRolling()
    {
        yield return new WaitForSeconds(_rollTime);
        trailRenderer.emitting = false;
        _isRolling = false;
    }```
valid minnow
heady iris
#

If madness is at 0.5, the weight is 0.5

valid minnow
heady iris
#

again, see the linked example

#

This will give you a point whose position is based on the balance between the four emotions

shell scarab
#

my solution also will if you just have 2 variables instead of 4 :p

valid minnow
heady iris
#

You must divide by the sum of all weights

valid minnow
heady iris
#

No.

valid minnow
#

or how many

#

?

heady iris
#

If all four emotions are at 50%, then each one has a weight of 0.5

#

So you would sum up the following:

valid minnow
#

yeah

heady iris
#
0.5 * [1,1] + 0.5 * [1,-1] + 0.5 * [-1,1] + 0.5 * [-1,-1]
#

Then you would divide by

#
0.5 + 0.5 + 0.5 + 0.5
#

In this case, you'd get [0,0] divided by 2

#

Suppose we had 100% weight on the [1,1] and [1,-1] emotions

#

[1,1] + [1,-1] = [2,0]

#

[2,0] / (1 + 1) = [2,0] / 2 = [1,0]

valid minnow
#

so multiply each emotion by its position, then divide it by each ones value added to each other

heady iris
#

Right.

valid minnow
#

oook lemme try

heady iris
#

Also, if the sum of weights is zero, just put the dot at [0,0]

#

Since you'll otherwise have a division by zero.

heady iris
#

maybe happiness and energy or something

#

happy + energetic = excited
unhappy + energetic = mad
happy + unergetic = tired
unhappy + unenergetic = sad

#

that would be a different system entirely, though

valid minnow
#

yeah

shell scarab
#

but right now happiness is exclusive to sadness so just say if 0, happy, if 0.5, neutral, if 1, sad

valid minnow
#

i just want the average positon based on each ones value

valid minnow
#

its kinda like how joysticks work

#

what i want i mean

heady iris
#

If you want to visualize four completely separate emotions, then you'll get some ambiguous results

#

if the dot is at the middle, that could be any balanced amount of all four emotions

valid minnow
#

i got this error

shell scarab
#

dividing by 0 or a really tiny number probably

valid minnow
#

right

shell scarab
#

no you don't

shell scarab
#

you can do, no extra function needed

if(denominator == 0)
  // dot at 0.5, 0.5
else
  // calculate
valid minnow
#

this should be it i think

#

i still get the same error

heady iris
#

well, unless you wrapped the rest of your code in an else down there

#

you're still trying to assign a bogus position to your transform.position

#

that triggers the error instantly

valid minnow
#

dh

#

duh

#

i think it works? maybe?

heady iris
#

well, are you actually doing anything with EmotionAverage?

#

it seems to me like you should do

#
emotionSum = MadAmount + ...
Vector2 target;
if (emotionSum < 0.001f)
{
  target = Vector2.zero;
}
else
{
  Vector2 positionSum = MadAmount * MadVector + ...
  target = positionSum / emotionSum;
}
EmotionDot.transform.position = target;
#

note that you can multiply a float with a Vector2

valid minnow
#

it works!

valid minnow
heady iris
#

yes. i noticed you were constructing a new Vector3 from individual components there

#

you don't have to do that

#

you can just multiply MadAmount with MadVector

valid minnow
heady iris
#

yes. you can still just multiply MadAmount with MadVector

valid minnow
#

it works but theres a bug idk how

heady iris
#

Vector2 can implicitly convert to Vector3

valid minnow
heady iris
#

Yes.

valid minnow
#

i tried that and it didnt work for some reason lemme try again

heady iris
valid minnow
#

ah it works now

valid minnow
heady iris
#

show your current code

valid minnow
#

to make it less spaghetti code

heady iris
#

oh, your vectors aren't right

#

They should be constants.

valid minnow
#

huh

heady iris
#

and I see a problem with my scheme now

#

so the idea is that the mad vector would just be [1,1]

#

so that if you were 100% mad, you'd be at [1,1]

#

(with no other emotions)

heady iris
#

suppose you're just 10% mad with no other feelings

#

0.1 * [1,1] = [0.1, 0.1]

#

but then you'd divide by 0.1 and be at [1,1]

#

actually, question:

#

suppose you were 50% mad and 50% happy

#

Where would you want the dot to be?

#

I see two reasonable locations:

  • halfway to the bottom
  • all the way at the bottom
heady iris
#

Your problem is that you don't update EmotionAverage if all of the emotions are at 0%

#

You set EmotionDot.transform.position, but then EmotionDotLocation() runs and sets the position again

#

So just make line 112 set EmotionAverage to Vector2.zero.

#

yeah, that's all correct, then.

valid minnow
#

uhh soo i need to update emotion average if all emotions = 0

heady iris
#

Right. Your code currently sets the transform, but that gets clobbered immediately when you call EmotionDotLocation

#

So just set the average to zero if the emotion sum is zero

valid minnow
#

i think this shouuuld work???

heady iris
#

No, that doesn't fix it.

valid minnow
#

oh

heady iris
#

set the average to Vector2.zero

valid minnow
heady iris
valid minnow
#

fixed??

heady iris
#

Where is this code?

valid minnow
heady iris
#

My suggestion was to change one line in setVectors

#
        if (MadAmount + SadAmount + HappyAmount + ScaredAmount == 0)
        {

            EmotionDot.transform.position = new Vector2(0, 0);

        }
        else
        {
            EmotionAverage = ...
        }
#

This should just set EmotionAverage to Vector2.zero

#

that's it

valid minnow
#

ah

#

thats more optimized prob

heady iris
#

i wouldn't say it's "optimized"

#

but it does make more sense

valid minnow
#

yeah

#

wait why are you not setting emotiondot = to emotion average? is it assumed its done elsewhere?

#

this makes more sense to me

#

seems to fix the issue tho!

#

looks like it works now ๐Ÿ™‚

#

thanks to everyone who helped me ๐Ÿ™‚

heady iris
#

but it is more reasonable to just do it right away

valid minnow
swift falcon
#

so if I have vector v and i put it in a pure quaternion V, should i just chop off the real part of V' = QVQ^-1 to get v' ?

heady iris
#

i don't understand what you're asking

#

are you asking about manually performing a rotation?

cosmic rain
#

Why would you put a vector in a quaternion?

heady iris
#

because Q * V * Q^-1 does remind me of how that works

swift falcon
#

i read that vectors can be represented as quaternions with no real part, so that you can do quaternion maths with them, but nobody ever told me how to get the vector back lol

heady iris
#

w is the real part, right?

swift falcon
#

yeah

heady iris
#

i'll do quaternion maths by hand at some point

swift falcon
#

pain ^

heady iris
#

but yes, I believe you take the products and then just lop off the real part

#

mildly confused by the notation: i'm seeing people write quaternions at [w x y z] when showing the math

#

that does match how you write a complex number

#

a + bi

swift falcon
#

yeah, took me a few fails to realize that w goes on the end in unity lol

heady iris
#

It matches how you typically use vector4's

#

xyzw

#

rgba

#

alternatively

cosmic rain
#

If you just multiply a vector by quaternion in the right order, you should get a rotated vector.

heady iris
#

yeah, Unity does that for you

#

Quaternion * Vector3

#

pentagon here is asking about doing the math by hand

cosmic rain
#

Like on paper?

heady iris
#

well, on the computer, just without Unity doing it for you

#

you just do some Hamiltonian products (multiply the two quaternions with the distributive property)

#

hey, that sounds remarkably easy...

swift falcon
#

yeah was just trying to get a more fundamental understanding of them

swift falcon
heady iris
#

yeah, that's how you're meant to use them in unity :p

#

oh yeah, and if you hit F12 to view how the * operator works, it does more-or-less exactly what's depicted in the above image

elder flax
#

how do rigidbodies move internally?

#

Im trying to do something involving mesh colliders on rigidbodies (which dont go obviously) as a test

#

my approach is proxy colliders

#

but when I move a proxy collider to the position of a rigdbody its far from perfect and jumps all over the place

#

this code works much better but it still has small artifacts (rigidbodies sitting on it still jump around)

#

coll being the target rigidbody (misnomer i know)

#

whats the best approach for this

cosmic rain
#

Assuming you mean the physics representation, their position is updated each fixed update based on their velocity. The transform and the rigidbody positions are not the same thing. The rb position is synced to the transform at some point. If interpolation is enabled, then it's definitely in update, since it needs to interpolate between last and next fixed position. If interpolation is not enabled, I'm not sure, but I'd assume it's in update as well.

elder flax
#

yeah how would I make a proxy collider follow it then

#

should I use rb.position somewhere

cosmic rain
#

Just setting it to the same position as an rb in update should work imho.

#

Though, I'm not sure if that updates the position of the collider in the physics world.

#

I don't think there's a need to use rb position, since it would be the same as transform position in update if I get it right.

#

I guess it would not be the same position in case of interpolation.

#

Generally, I'd avoid moving non convex mesh colliders at all...

#

I always say that if your implementation is fighting the engine, then you're doing something wrong and there's probably a simpler way compatible with the engine.

broken light
#

Any one know how to extract a mesh's submesh to be its own individual mesh

#

i cant figure it out because if i extract the slice of vertices the triangles wont have the correct indices anymore

#

so its a bit of a messy problem

cosmic rain
#

Mesh.GetIndices(int submesh) should get you an array of the submesh indices.
Is there any problem with using that?๐Ÿค”

broken light
#

No that's fine but the triangle indices won't start at the right place

cosmic rain
#

Wdym by that?

broken light
#

Well i also need the tris array to go with it that correctly point to the right vertex index

#

Since they point to their position in the original mesh

cosmic rain
#

Indices are the tris. You get a sequence of 3 indices that make up a triangle.

cosmic rain
broken light
#

Right but my new mesh the verts start at 0 not where the submesh started

cosmic rain
#

If you need to split that into separate buffers, you'll need to extract them and recalculate the indices.

broken light
#

That sounds complicated

leaden solstice
#

There is applyBaseVertex flag, probably what you want?

#

In Mesh.GetIndices. Default is true so youโ€™d want to set it false

broken light
#

What's the difference to that and get triangles function

leaden solstice
#

Should do same thing if your mesh topology is triangle

broken light
#

i dont follow what that means i would assume all indices follow triangle topology for meshes

leaden solstice
#

Not necessarily, you could make mesh with Quad topology , etc

#

Though not much used

broken light
#

i see

#

ill try it

#

last time i attempted this i had out of bounds errors

#

which was odd

#

is there no get vertices per submesh ?

#

or will i have to do that manually

leaden solstice
#

Well submeshes can share vertex buffer

broken light
#

ah true

#

so it cant even be guarenteed the vertices will be all sequentially together in the mesh to extract?

leaden solstice
#

Thatโ€™s why applyBaseVertex is true by default

#

You canโ€™t really guarantee and they could overlap yeah

broken light
#

because i was thinking of using array slice with baseVertex + vertexCount

#

that sounds like a tricky problem then

quaint rock
#

what is the usecase for this, like if its a mesh you built in code you can control this stuff

#

if not, why not fix it in a 3d package first

leaden solstice
#

Yeah depends on how your mesh formed

broken light
#

im copy pasting the mesh along a path and want to make it one single mesh

#

so i want to combine each similar submesh together

quaint rock
#

so for doing a mesh along a path, i would literlaly just use a ring of verts

#

like just the profile

broken light
#

huh

quaint rock
#

and build it all out in code

#

but that is assuming you want to bend it along the curve

leaden solstice
#

I mean base vertex + count would have all vertices that submesh uses

#

But plus possibly unused vertices

#

And removing them would be pain ๐Ÿ˜„

#

Shifts index around

broken light
#

this is what im trying to do on the right

#

each colour represents a submesh

#

what unity does is the left if i just copy paste and combine

#

it creates tons of submeshes

#

this is 4 of the same mesh copy pasted along a line for example

leaden solstice
broken light
#

so what im thinking is get the submeshes individually as a mesh and copy paste them along the line then combine that submesh ... do that for each submesh then finally combine those combines to the final mesh

leaden solstice
#

There is flag too, mergeSubMeshes ๐Ÿค”

broken light
#

yeh then i lose ALL submeshes so i would only have 1 submesh

#

theres no "preserve like submeshes" kinda option

quaint rock
#

why is that so important

broken light
#

because they have different materials

quaint rock
#

why not have 2 meshes as a result

#

that are each combined

broken light
#

because they each one has to be a gameobject

leaden solstice
#

Combine submeshes that uses same materials first each

#

Then make final mesh with those ?

broken light
#

which was why i was asking about how to get the vertices correctly

quaint rock
#

but why provide it as a mesh with 2 sub meshes

leaden solstice
#

You can set submeshIndex in CombineInstance

quaint rock
#

jsut provide 2 meshes copy each one

#

combine

cosmic rain
#

So are these original meshes external assets?

quaint rock
#

then combine again

broken light
leaden solstice
#

So you can cherry pick what submesh you wanna combine

#

By material

#

Repeat per material then combine as final mesh preserving submesh

broken light
#

in order to combine submeshes i first need to extract the submesh data

#

to lerp along the path

leaden solstice
#

no you can just pass the submesh index when you combine

#

๐Ÿค”

cosmic rain
#

I mean, you could go over each submesh and create a triangle struct for each triangle holding 3 vertices. Then just use these triangles collection to create a new mesh...

quaint rock
#

feels its being over thinked

broken light
quaint rock
#

like do everyting twice then a final combine that does not merge submeshes

limpid steeple
#

Does anybody have any idea why I can do this:

_material = _renderer.material;

I am aware that renderer.material creates a new instanced material and assigns it to the renderer at this point, then I cache it in _material. However, later I try _material.SetColor and it does not affect the renderer? Upon debugging I see that the renderer's material says (Instanced), but the instance ID does not match the one I see in _material in the debugger. So modifying _material is modifying it, but it's not the material on the renderer for some reason. I don't know the reason.

I've put a conditional breakpoint in Renderer.material's setter and have confirmed that nothing else is assigning to the material on this renderer.

broken light
#

this was my original attempt:

 for (int s = 0; s < submeshes; s++)
            {
                var tempMesh = Object.Instantiate(mesh);
                var submesh = mesh.GetSubMesh(s);
                Debug.Log("Submesh: " + (s + 1));
                Debug.Log("Triangles => From: " + submesh.indexStart + " to " + (submesh.indexStart + submesh.indexCount));
                Debug.Log("Vertices => From: " + submesh.firstVertex + " to " + (submesh.firstVertex + submesh.vertexCount));

                int[] tris = mesh.triangles[submesh.indexStart..(submesh.indexStart + submesh.indexCount)];
                Vector3[] verts = mesh.vertices[submesh.firstVertex..(submesh.firstVertex + submesh.vertexCount)];

                Vector3[] newVerts = new Vector3[submesh.vertexCount * ((int)path.Length + 1)];
                int[] newTris = new int[submesh.indexCount * ((int)path.Length + 1)];

                for (int i = 0; i < path.Length; i++)
                {
                    int triIndex = i * submesh.indexCount;
                    int vertIndex = i * submesh.vertexCount;

                    var t = i / path.Length;

                    for (var v = 0; v < verts.Length; v++)
                    {
                        var time = t + range * verts[v].z;
                        var p = path.Lerp(time);
                        newVerts[vertIndex + v] = p;
                    }


                    for (int tri = 0; tri < tris.Length; tri++)
                        newTris[triIndex + tri] = tris[tri] + submesh.vertexCount * i;

                }
                tempMesh.vertices = newVerts;
                tempMesh.triangles = newTris;
                tempMesh.RecalculateNormals();
                tempMesh.RecalculateBounds();
                combines.Add(new() { mesh = tempMesh });
            }
#

but it was a big flop

leaden solstice
cosmic rain
broken light
quaint rock
#

then assign it back to material and cache it

broken light
#

what a pain!

leaden solstice
broken light
#

also have to make sure when i do that the verts are in the right place

leaden solstice
#

Then combine those combined submeshes

broken light
leaden solstice
#

WHY

broken light
#

wdym why

#

the mesh you add to the combine would need to be containing the info of the specific submesh not the whole object

leaden solstice
#

You donโ€™t even need vertices with this

broken light
#

๐Ÿค” i dont follow

leaden solstice
#

Just use original mesh + submesh index

#

Then combine will take info from that submesh

limpid steeple
broken light
#

maybe im not following the logic

quaint rock
leaden solstice
#

Thatโ€™d be separate concern?

#

You can preprocess that

#

Then combine however you want

limpid steeple
quaint rock
#

normally would ask you to breakpoint and ensure its not being set again by something else

#

but you said you did that already

cosmic rain
hexed coral
quaint rock
#

which renderer are you in?

broken light
hexed coral
#

If the material is not working properly, setcolor won't work as well

limpid steeple
#

Yeah I breakpointed in .material's setter with a conditional breakpoint that logs a stack trace, it only gets assigned once.

#

MeshRenderer

hexed coral
#

What is the material?

quaint rock
#

also what are you calling to set props

#

some things only work if the shader has the correct property names

#

also could there be a material propertly block overriding ?

limpid steeple
#

_material = new Material(_renderer.sharedMaterial);
_renderer.material = _material;

...

_material.SetColor(Color.red);

(Color stays black).

#

No property blocks, I'm actually trying to migrate away from those now that I'm on the SRP batcher.

hexed coral
#

which material is it

#

what shader does it use

limpid steeple
#

Trying to figure out what the new workflow is. It's a shader graph.

cosmic rain
hexed coral
#

show us the graph

limpid steeple
#

Yeah I've been looking at it, it does not change color. Yes the property is exposed.

quaint rock
#

what is the prop named?

limpid steeple
#

The problem is pretty certainly that _renderer.material and _material have different instance IDs so I'm setting the color on a totally different material somewhere. I'm just not sure why assigning a material doesn't...assign the material.

hexed coral
#

don't you need to pass a property id here? _material.SetColor(Color.red)

limpid steeple
#

Yeah, sorry that was pseudo code.

quaint rock
#

but you are acccess .material again to check its id

quartz folio
#

Calling .material makes sure there is a new instance assigned to the renderer

quaint rock
#

thus creating a new one

#

only ever do .material once to set or get it

#

then use the cached one only

leaden solstice
#

That part so gross

limpid steeple
#

Yeah I only do it once, I'm comparing the ID of _material, not renderer.material, to the material I see in the inspector.

cosmic rain
quaint rock
#

also ensure you are setting it on the real name or id of the prop not the pretty name

limpid steeple
#

Yeah I'm using the reference.

hexed coral
#

Tbh we will be making shots in the dark, as long as you don't show us the actual code/graph

limpid steeple
#

I've set colors many times with MaterialPropertyBlocks, just trying to figure out how instanced renderers work in the SRP batcher.

#

The problem isn't anything with the shader graph or how I'm interacting with it, it's that there are two materials, one I'm caching, and another one coming from somewhere on the renderer.

quaint rock
#

but you are hitting problems and cant finding them with that reasoning

cosmic rain
#

There shouldn't be any difference with working with materials between render pipelines.

quaint rock
#

so test all assumptions

cosmic rain
#

Aside from properly names maybe

quaint rock
limpid steeple
#

^

#

Anyway, I'll keep plugging away, thanks for listening anyway.

cosmic rain
#

Yeah, but I'm not referring to MaterialPropertyBlocks. Just getting, setting and editing the materials themselves.

quaint rock
#

yeah that all works indentically

#

since all the time so i can get things to batch i will make runtime instances of things with common props and assign them all to renderers

tall pewter
#

Hey everyone, I'm here looking for suggestions, I want to integrate AI into my FPS game, I want to create behaviors like patrol, attack, attack force, and alert state behaviors, but especially the behaviors I've been working on are cover behaviors. , and behavior of flanking the player, but I feel that everything has been getting more and more complicated for me, I want to know if you can recommend any asset from the Unity Asset Store that will help me with the basic behaviors but that will allow me to create my own advanced behaviors.

At the moment, the ones that I have seen that are closest to what I want are these two assets "Invector FSM AI Template" and "Behavior Designer - Behavior Trees for Everyone", if someone has used them and can tell me which of the two I want can help me meet my goal of advanced behaviors without using ML, or if you can recommend me a new one please.

broken light
#

if i set to true

#

then all submeshes get merged which is equally not what i want

#

because the original mesh had 2 submeshes

#

so the final result should have 2 submeshes aswell

leaden solstice
broken light
hexed coral
#

What I can recommend is taking some time to study StateMachines, and how experienced developers make them

cosmic rain
hexed coral
cosmic rain
#

If it's open source or has a clear documentation I think it's totally worth the time saving.

hexed coral
#

Most open source ones I found were poorly maintained, which lead me to go bug fixing myself, when I could have spent less time making the thing from scratch

#

And also improving my code skills on the process

cosmic rain
#

There's a reason why we buy things from other people instead of making them from scratch. The same applies to software components.

hexed coral
hexed coral
cosmic rain
#

I find that I can learn a lot of new things looking at other people code rather than my own.

limpid steeple
cosmic rain
hexed coral
limpid steeple
#

That's a pretty wide generalization though.

hexed coral
hexed coral
limpid steeple
#

I've been working with Unity for over ten years and I still grab assets, they save you from having to write a bunch of boilerplate stuff so you can just make your game.

limpid steeple
#

There is no such thing as a bug free game.

hexed coral
#

there absolutely is

cosmic rain
cosmic rain
hexed coral
#

You can argue all you want about the semantics of bug free, but on the eyes of the player if he never saw a bug then it's bug free

cosmic rain
#

Anyways, the point is: you should decide for yourself wether it's worth buying an asset or not. We provided the pros and cons, but ultimately it's a matter of preference.

chilly horizon
#

Wow just realised the award thing is on! Happy for all those people that made it and the people who helped! โค๏ธhugs

#

Bye ( looks like a fun concert ๐Ÿคฃ๐Ÿคฃ) ๐Ÿคท๐ŸŒป

floral geyser
#

This is a kind of niche question and I'm really struggling here, but how can I modify the submesh indexes of an imported mesh?

cosmic rain
#

Modify in what way?

#

And what do you hope to achieve with that?

floral geyser
#

Re-order them, I figured it'd be an import setting or something

#

So, I'm making destructible props, and the way I'm doing it is by creating a particle effect that takes submesh 0 (because it can only handle one submesh) and creates a particle based off it

#

Problem is, I don't understand how Unity determines what index 0 is

cosmic rain
#

Submesh data contains the index offset.

#

You can get the sumbmesh index offset from the Mesh API

floral geyser
#

I can tell easily enough which submesh is assigned to what index, but that information isn't useful because I need to create a standard

#

Otherwise I'd need to check every mesh for every prop in the game, and manually set which submesh index is the important one

#

If I could just set the important submesh to be index 0, that'd simplify it a lot

#

Do you happen to know how Unity determines which submesh is index 0? Or does that info come from the file itself?

#

It doesn't seem to be determined by material order, or by vertex count

cosmic rain
#

If you want to standardize it, you'd need to tell that to your 3d designers, or edit the mesh in 3d software manually.

tall pewter
# hexed coral None, Unity assets that are code related will hinder your learning progress **an...

I understand how to make a state machine, I'm just looking for a plugin that makes it easier for me not to reinvent the wheel, I try to keep my development as efficient as possible without reinventing what already exists, although I understand what you mean but I can't stop thinking In the large amount of work that I can save if I use a tool that can help me, really in the Active Store there are many professionals who are perhaps doing things better than me.

glacial cliff
#

Why do people use an 'Orientation' gameobject to store their character controller's rotation?
Why not just rotate the parent gameobject?

cosmic rain
#

Because they all watched the same tutorial that does that๐Ÿคทโ€โ™‚๏ธ

glacial cliff
#

wouldn't surprise me haha

#

Still, its an odd thing to keep replicating

cosmic rain
#

Well, you don't notice it if you copy paste the code and the tutorial as is without understanding it.

spring creek
covert turret
#

So setting transform.position on a parent game object doesn't move children object colliders ๐Ÿ’€

#

Does anyone know how to workaround this?

novel raven
#

so im currently trying to figure out some asynchronous code
if i call an async Task SlowFunction() from a void without awaiting it should run without holding up the program correct?

ashen yoke
#

yes

cosmic rain
covert turret
#

they're neither of those :\

#

Weird thing is, if I do something that changes the way it functions, it does update to the new 'last' position..

#

ie add rb to child and remove it

novel raven
# ashen yoke yes

ah, is there any reasons why it wouldn't do that? as currently the Task seems to run synchronously causing a 14s lagspike

covert turret
#

yeah there is definitely some fuckery going on

cosmic rain
covert turret
#

pretty much all I'm doing is transform.position setting every update on a gameobject to follow the player

cosmic rain
covert turret
#

I will send clip hold on

novel raven
#

it gets metadata from mp3 files (im making my own music player)

async Task ReloadAllSongs(){
        Debug.Log("Reloading all songs");
        DateTime start = DateTime.Now;
        //reload all songs
        songs.Clear();
        FileSuper fs = new FileSuper("AirPlayer", "ReplayStudios");
        char [] invalidChars = Path.GetInvalidFileNameChars();
        Save save;
        TagLib.File tagFile;
        for(int i = 0; i < paths.Count; i++){
            string[] files = Directory.GetFiles(paths[i], "*.mp3", SearchOption.AllDirectories);
            for(int j = 0; j < files.Length; j++){
                try{
                    Song song = new Song(files[j]);
                    tagFile = TagLib.File.Create(files[j]);
                    song.name = tagFile.Tag.Title;
                    song.artist = tagFile.Tag.FirstPerformer;
                    song.album = tagFile.Tag.Album;
                    song.albumArtist = tagFile.Tag.FirstAlbumArtist;
                    song.art = PlsImage(tagFile.Tag.Pictures[0]);
                    string safeName = song.name; //filter to only letters and numbers and spaces
                    foreach(char c in invalidChars){
                        safeName = safeName.Replace(c.ToString(), "");
                    }
                    save = await fs.LoadFile($"songData\\{safeName}.dat");
                    if(save != null){
                        song.playcount = (int)save.GetInt("playcount");
                        song.rating = (int)save.GetInt("rating");
                        song.dateAdded = DateTime.FromBinary(long.Parse(save.GetString("dateAdded")));
                        song.lastPlayed = DateTime.FromBinary(long.Parse(save.GetString("lastPlayed")));
                        song.lastSkipped = DateTime.FromBinary(long.Parse(save.GetString("lastSkipped")));
                    }
                    else{
                        song.playcount = 0;
                        song.rating = 0;
                        song.dateAdded = DateTime.Now;
                        song.lastPlayed = DateTime.Now;
                        song.lastSkipped = DateTime.Now;

                        save = new Save();
                        save.SetInt("playcount", song.playcount);
                        save.SetInt("rating", song.rating);
                        save.SetString("dateAdded", song.dateAdded.ToBinary().ToString());
                        save.SetString("lastPlayed", song.lastPlayed.ToBinary().ToString());
                        save.SetString("lastSkipped", song.lastSkipped.ToBinary().ToString());
                        await fs.SaveFile($"songData\\{safeName}.dat", save);
                    }
                    tagFile.Dispose();
                    songs.Add(song);
                    Debug.Log($"Loaded {song.name} by {song.artist}");
                }
                catch(Exception e){
                    Debug.LogError(e);
                    continue;
                }
            }
        }
        DateTime end = DateTime.Now;
        Debug.Log($"Loaded {songs.Count} songs in {(end - start).TotalSeconds} seconds");
    }
covert turret
#

observe collider prior to start game

#

then see that there's invisible boundary where it was at the start (I cant walk past it)

#

despite the gizmos itself showing the collider moving with player

limpid steeple
#

I've been finding conflicting information, does the getter for Renderer.material allocate every time you access it, or just the first time you access it on that renderer?

limpid steeple
#

Okay that's not so bad.

ashen yoke
#

mechanism just protects source asset material

#

no point in cloning after first

covert turret
cosmic rain
novel raven
#

first tick

ashen yoke
novel raven
cosmic rain
cosmic rain
covert turret
#

But I need it to be colliding

#

ie I want raycasts to hit it

cosmic rain
covert turret
#

No, it stops colliding with my player strangely enough, I suppose its related to how its just staying in its original position

#

which makes sense if I disable it that the boundary disappears as well, and I can walk through it

novel raven
cosmic rain
covert turret
#

I can try

cosmic rain
covert turret
#

but I think i will need to do rigidbody move instead of transform.position setting

cosmic rain
#

Are you moving it with transform?

covert turret
#

yes

#

Im just doing gameObject.transform.position = new position

novel raven
#

well thats useful, tho ill have to figure out how to actaully fix it

ashen yoke
cosmic rain
#

Okay, then obviously it wouldn't respect physics properly. It could be why it's actually not updating the physics position.

covert turret
#

weird nuance

cosmic rain
covert turret
#

maybe it says somewhere in documentation

#

(i dont remember all details of documentation)

cosmic rain
#

Which points out that your load and create methods aren't actually async.

hexed coral
# tall pewter I understand how to make a state machine, I'm just looking for a plugin that mak...

The sole reason I'm recommending to avoid the asset store is because I have been in your shoes, and what I've learned is that this "time saving" doesn't exist, using an asset from the store will not save you time, it will only hinder your learning and give you bugs in the future.

Just to be clear, I'm not here making the argument that you should do everything by yourself, I work with Unity by choice, I could have made a game engine but when I started I couldn't do a better job than a group of senior software engineers.

My argument here is against the Unity Asset Store, there's no quality control there, the reviews are made by people that are basically anonymous - regardless of the rating (1-5) you don't know if the person who reviewed is qualified to do so, it could be an amateur who has no idea what he's doing (and of course it could also be a experienced developer).

ashen yoke
#

very one sided argumentation, shaky

cosmic rain
novel raven
#

well it seems like the major issue is coming from formatting 636 byte arrays into sprites

cosmic rain
#

Since your API doesn't seem to do that.

novel raven
# ashen yoke which api does that?

this function

Sprite PlsImage(IPicture picture){
        
        byte[] data = picture.Data.Data;
        Texture2D texture = new Texture2D(2, 2);
        texture.LoadImage(data);
        return Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0, 0));
    }
ashen yoke
#

unity api call, synchronous

cosmic rain
#

Yeah, this is just a synchronous method. If you call 600 of them at once, that would obviously take a lot of time.

#

To make it clear(if that's the misunderstanding), async await in unity is running on the main thread. Similar to how coroutines do. If you expect your whole method to run on a separate thread that's not gonna happen.

ashen yoke
#

even if it did, to use unity api it would bring it to the main thread

cosmic rain
#

Would probably cause errors and crash, but yeah.

novel raven
cosmic rain
#

Not sure what that means. I guess you're using a different synchronization context that actually executes the method on a different thread?๐Ÿค”

novel raven
#

tldr: async .NET framework code is synchronous in .NET core, .NET core async just crashes in .NET framework

cosmic rain
#

I don't know much about using async await outside unity and especially with different dot net versions. All I know is that unity overrides some of the async await stuff to run on the main thread by default.

uncut path
#

My 'Wire Gen' Configurable Joints keep getting all twisted. why am i having such a hard time Locking Z?

frosty shuttle
#

Can someone help me fix this script i got from a vollumetric lighting package?

sly gate
#

i wanted to add sounds to my game, but i think the way i implemented the audio systems might be a bit flawed, but im not really sure why. Basically, i made a static singleton with every sound that i need to reference and then when i need to play a certain sound, like an enemy being hit for example, i get the enemyhit audio clip from the singleton and put it into the enemy's audio source, and then immediately play it;

            sound.Play();```
 but it doesnt always work correctly, sometimes the sounds just dont play, sometimes they have a huge delay, and sometimes they make my cursor go into the loading cursor for some reason, is there something im doing wrong?
limpid steeple
#

If I create a material instance using renderer.material.whatever, then call Object.Destroy(renderer.material), does the renderer revert back to its shared material, or go magenta or something?

#

Looks like it will go magenta. blegh.

frosty lark
regal epoch
#

hey guys i want to make a simple multiplayer card game. the script would mostly run locally, i just want a few numbers to be shared between the devices (like card number and round number). do you guys know of any tutorials that could explain some basics about this?

main shuttle
regal epoch
lean sail
regal epoch
#

Fair haha. I guess I'll pick one then :) thanks

swift falcon
#

Is there some way to extend a class (eg add members) from outside the class definition? Like if I wanted to add a method or something to one of the UnityEngine or System classes

ashen yoke
#

there are extension methods, but its not the same as a class method

drifting root
#

How fast is converting int to uint?
I just want to get use of enum with layers stored in it. So if I want to get the Terrain layer, I will be able just to layers.Terrain (not 1u << some number). But I wonder if it is a little expensive if I will use (uint) conversion quite often?

ashen yoke
#

both int and uint have the same size, the conversion is just changing some bits in memory

#

its not a little expensive

simple egret
#

Almost instant. What a cast does is nothing in memory, only tells "the stuff at this address can be interpreted as something else". And here since int and uint are both value types with the same length in bytes, I wouldn't be surprised if the compiler gets rid of the type check entirely

ashen yoke
#

its so inexpensive that its not a factor at all

drifting root
#

Understood, thanks. Just wanted to be sure in that idea :)

ashen yoke
#

this can be true if its a positive number, but compiler cant know that

#

plus its still a value copy

simple egret
#

Even for negative numbers, it does not do any checks. You just get a really high number since it underflows

#

uint Method(int x) => (uint)x;

ldarg.0
ret

Load the value, return it. Can't be faster than this

ashen yoke
#

right, thanks

drifting root
#

Is there a way I can put ~0u in enum? To make an "everything" layer there

heady iris
#

are you already using the [Flags] attribute?

drifting root
#

No. To be honest I haven`t heard of it before you said :)

heady iris
#

Each value in an enum gets an integer assigned to it

drifting root
#

So I just need to put that flag and than sum all the layers I need for the "Everything" value

heady iris
#

by default, these are just sequential numbers

#

(or wait, do you know about using powers of two already?)

drifting root
#

Well, that phrase I do not understand

#

Maybe I do, but I am not sure

heady iris
#
public enum MyEnum {
  Foo = 0,
  Bar = 1,
  Baz = 2,
  Buz = 3
}
#

These are the default values you get when you define an enum