#archived-code-general

1 messages · Page 391 of 1

reef garnet
#

Hi if anyone is familiar with Wwise need some help, we're adding an RTPC to control pitch in the following code

[Header("Sound Settings")] 
    public string engineSoundID = "Speed";

    public float truckSpeed = 0;
    public float maxTruckSpeed = 100;
    
    public void UpdateSpeed(Component sender, object data)
    {
        if (data is not float speed) return;

        truckSpeed = (speed / maxTruckSpeed) * 100;
        
        Debug.Log(truckSpeed);
        AkSoundEngine.SetRTPCValue(engineSoundID, truckSpeed, gameObject);
    }```
 
we were using a single main bank and it worked properly
we have now switched to seperating the banks by category, so now a Vehicle Sound bank is attached to the truck where the AKAmbient components are as well, the sound plays but the RTPC no longer changes the sound and we don't know why
So to reiterate, the only thing we changed before it stopped working was making seperate banks and this one is dedicated to the Vehicle sounds
shell scarab
#

In a coroutine:```cs
while (time < 1)
{
time = Mathf.Clamp01(time + Time.smoothDeltaTime / (EnableTime * 2f));
_material.color = Color.Lerp(Color.clear, toColor, time);
_imageMaterial.color = Color.Lerp(Color.clear, toColorImage, time);
yield return null;
Debug.LogError(_imageMaterial.color);
}

The color visually changes, but the log prints the same color the entire time? I logged the time variable and it is increasing from 0 to 1. What could be going on?
heady iris
#

I don't understand why time would slowly increase from 0 to 1, given this code

#

It's just dividing Time.smoothDeltaTime by EnableTime

#

If the game's framerate is constant, then time will also be a constant

shell scarab
#

my bad, i messed up when copying it. Add time + on the inside of mathf.Clamp.

heady iris
#

I see

#

Make sure that it still behaves the way you think it does

#

(time goes from 0 to 1, but _imageMaterial.color isn't changing)

#

make sure that you have "Collapse" turned off in the console so that each message appears on its own line

#

After you check this, show me the code with all log statements included

fallow quartz
#

If i want to make a boss in a game with AI and depending of some variables it decides what player to attack (It is multiplayer) is it better to use a state machine, a behaviour tree or something else?

shell scarab
#

yea I have collapse turned off. The thing updates visually but that reads as if _imageMaterial.color is the color it is before this coroutine starts.

Specifically the problem I'm having is that the color is flickering during a coroutine that does 3 things:

Fade the material up
wait
Fade the material down slightly.

during the 'fade up' phase it visually goes from clear to toColor.
before the 'wait' phase it logs one color, then after the wait phase it logs a different color and visually changes to that color; that color being the color it was before the coroutine started.
during the 'fade down' phase it goes from toColor to another color. Again it does this properly visually.

However the wait phase seems to cause it to appear as if it flickers. Nothing else is changing the color. There is a timeline configured to play later, but that is disabled. The reason I'm having to do this jank in the first place is because the timeline won't "let go" of the object once it completes playing even with wrap mode set to none.

@heady iris

heady iris
#

yes, animators (which I'm pretty sure is what the timeline uses to actually change things) are very possessive (:

shell scarab
#

yes, except at this point none of them are enabled or have been enabled yet

#

animator or playable director

heady iris
#

Oh, I see what it is

#
 while (time < 1)
{
    _imageMaterial.color = Color.Lerp(Color.clear, toColorImage, time);
    yield return null;
    Debug.LogError(_imageMaterial.color);
}

You're logging the color one frame after you set it

#

The timeline has gone and set the color in the meantime

#

If you logged it before the yield return null, you'd see the expected value

shell scarab
#

the timeline is inactive and animator inactive, and the playable director is not set to play on awake and has no timeline asset even set at this point.

heady iris
#

Check this by moving the log statement before the yield

shell scarab
#

this animation system is horrible. They need to have some method that can be called to "release" the object

#

so I need to add the playable director and animator at runtime??

#

ok, I tried removing the animator and director however the flicker still occurs.

#

the debug logs are now correct however.

heady iris
#

Perhaps something else is controlling the color as well

#

Can you share the entire script that this is from? I want to see where _imageMaterial comes from

shell scarab
# heady iris Can you share the entire script that this is from? I want to see where `_imageMa...

I can't share the entire script but I can answer your questions and show you most of it. I'm the one that wrote it all, and I know nothing else is touching this object as I haven't programmed anything to do so nor added any components (except for that animator and director) and it's not even pushed to our repo yet.

_imageMaterial comes from this:

[field: SerializeField] private Renderer BackImage { get; set; }


    private void Awake()
    {
        GrabReferences();
    }

    private void GrabReferences()
    {
        if (!_playableDirector)
            _playableDirector = transform.parent.GetComponentInChildren<PlayableDirector>();
        if (!_material)
            _material = transform.parent.GetComponent<Renderer>().material;
        if (!_imageMaterial)
            _imageMaterial = BackImage.material;
    }
heady iris
#

And what's the problem, again? The renderer using _imageMaterial is flickering?

shell scarab
#

yea the color

heady iris
#

Flickering is interesting, because that implies that two different things are taking turns

#

normally, if two things are controlling the same property, one will always run second and thus win every frame

shell scarab
#

it's almost as if it "forgets" the color once it starts the wait coroutine which is bizarre as hell

heady iris
#

Perhaps you're starting multiple coroutines. It's hard to say much without seeing more code.

shell scarab
#

ok hold on, are animators supposed to have a "hold" on the object when they're inactive and have never been active before?

modern creek
#

I've looked through the docs but can't find anything built in.. anyone know if there's an (easy) way to do a ballistic motion tween in DOTween? I have a start/end Vector3 and a desired height, but I'd like to avoid rolling my own because bAd At MaTh and I'd have to google up the physics.

#

FWIW it's for an object that doesn't have a rigidbody on it, and needs to end up at the "to" Vector3

#

one of the other mice throws a grenade

#

(fwiw the x/z locations are coplanar, which should make the math easy)

heady iris
modern creek
#

i'm trying DOJump but it looks... off

#

I have the ease set to linear, which might be the problem

#

lemme video, standby

wicked scroll
#

yeah that'll look weird

#

one simple thing you can do is expose an AnimationCurve in the editor, shape it how you want, and then interpolate along that as the trajectory

modern creek
#

hm.. i haven't done that before.. does that play nice with DOTween?

#

i'm assuming interpolate it vertically and handle the x/z movement linearly with dotween? or just do it all with animationcurve

#

hm actually DOJump looks ok if I speed it up

#

slowmo just looks off but .. maybe it won't matter too much since .. honestly, who looks TOO closely at ballistic motion of grenades in flight? 😛

wicked scroll
#

ummm I think I would probably just use the curve? I'm sure you could get it to work with dotween but you might need to sample from the curve and pass those values in

wicked scroll
#

or use an animationcurve to define a custom one that fits your case (and now a word from our sponsor: AnimationCurves)

modern creek
#

yeah the problem is i want the x/z motion to be linear, but the jump to be parabolic

wicked scroll
#

that's exactly what DoJump does, right?

#

oh i see what you're saying

modern creek
#

that's what I thought? but the jump seemed stuttery when i played it linear

#

like floaty at the top

wicked scroll
#

is that really what you want? does anything move like that?

#

does it even make sense as a statement?

#

this is their example in the docs

modern creek
#

I mean, that's my understanding of newtonian motion? that the projectile moves linearly in the x/z plane and quadratically in the y axis

heady iris
wicked scroll
#

mathematically, yes? but not like...interpolatingly?

modern creek
#

i might just be overthinking this

#

this is DOJump with linear

#

it looks fine?

heady iris
#

That looks correct to me

#

Although, it might not have the correct value for gravity

wicked scroll
#

yeah, and then if you want to change the character of the motion, you change the speed over the course of the curve

#

a rocket might start slower and then be going really fast by the end of its arc or whatever

modern creek
#

lemme make it a bit longer distance and slow it down.. but honestly, maybe i'm just overthinking this.. it looked odd to me when I set the travel time to 5sec to examine it, but now that i sped it up a tiny bit, it seems to look just fine

heady iris
#

(i.e. different curves may have faster or slower vertical acceleration depending on the shape)

wicked scroll
#

doing this kind of thing with tweens, you always end up having weirdness unless you scale the time with distance in some way

heady iris
#

You can calculate how long the tween should take given the desired horizontal velocity and the distance

#

I see that DOJump takes a "jump power", which is the maximum height you reach

modern creek
#

yeah, I mean, I could do a little extra math and up the height for longer distances (seems to make sense?)

heady iris
#

To pick the correct jump power to get a consistent gravity for any range, you'll basically be doing the kinematic equations of motion again :p

wicked scroll
#

keep in mind that you can also blend tweens, so if it makes more sense to have a tween for your horizontal motion and then another one for your vertical that you blend together and tweak independently, you could do that

modern creek
#

I think the motion looks natural, but yeah, it's gonna need to have more jump power if it's farther away

#

looks like he's got a 100mph fastball

wicked scroll
#

hehe yeah

modern creek
#

actually maybe i should be just doing the math and setting duration AND height based on distance

modern creek
#

like, it's gonna look silly if it's 1 hex away and traveling in slowmo while going 20 hexes in fastmo

wicked scroll
#

alternately, sometimes the best solutions are design solutions

#

is it a 'lobbed' ability? give it a minimum range and tune it so that it looks right for long range

modern creek
#

unfortunately i'm locked in for the design.. it's for a board game and the range is already set

wicked scroll
#

lobbing something comes baggage, so maybe that's a good constraint to enforce anyway

#

ah well as you were then

modern creek
#

rather, it's for a video game [demo] for a board game that already exists

latent latch
#

no clue about dotween but I usually just lerp an animation curve

heady iris
#

Maybe try picking up a ball and throwing it :p

modern creek
#

"hey guys thanks for the work but could you recall the hundred thousand copies you printed because I can't get grenades to look nice" probably won't fly 😛

heady iris
#

that'll show you how the horizontal and vertical speeds vary with range

wicked scroll
wicked scroll
latent latch
#

also from the previous topic, another thing you can really use the timeline for

heady iris
#

I trued using the timeline once and then decided not to use the timeline 😅

#

i like my code

latent latch
#

timeline is just visual scripting for tweening ;)

wicked scroll
#

yeah but isn't that what animating is too?

latent latch
#

animation itself is magic and it's something I don't question

heady iris
#

i know just enough about Playable stuff to hurt myself

wicked scroll
#

maybe I should actually look into it, but timeline always sounded like 'do you wish your game were as entirely driven by gameobject references and unity-specific asset formats as possible?' and my answer is always 'no pls'

heady iris
#

i also make highly complex VRChat avatars, so i'm way too familiar with Mecanim

#

did you know that you can animate animator parameters?

#

you can do math in the animator!

#

and Mathf.MoveTowards-esque linear motion!

#

(jesus christ i wish i could just write C#)

shell scarab
#

Ok i solved it. When I removed the PlayableDirector it was causing a null reference in my on enable which i didnt catch because of log bloat 🙃 once i commented the line out it began working as it should because the onenable disabled part of my update loop which does modify the color.

heady iris
#

ahh, that'll do it

#

By the way, if you want to "beat" the animator, do your work in LateUpdate

wicked scroll
heady iris
#

i have started writing editor scripts to generate animator layers for common tasks (like linearly approaching a value)

#

it's so cursed

#

it's like using a shotgun to dig holes in your garden because you don't have a shovel

crisp bronze
#

Does anyone have an issue with Intellisense not working on VSCode when offline?

heady iris
#

Yeah.

#

VSCode frequently decided that it wanted to download the .NET SDK

#

that's controlled by the .NET Runtime Install Tool

#

I could never convince VSCode to just use a manually-installed SDK -- it always ignored my settings and wanted to manage the installs itself

heady iris
karmic herald
#

question about netcode for gameobjects - the end result i want is essentially just everything stays on the client but the players on the server can see each other-like, gameobjects that get another player's position and move themselves to it on the client, without sharing everything else like scene info

relevant resources appreciated

#

or does it just do that automatically

latent latch
#

if you're just using network gameobjects a lot of that is already done for you

#

also what exactly is the question

karmic herald
#

how to achieve what i described

#

idk maybe im overthinking it

latent latch
#

network gameobjects and its API is the answer then

karmic herald
#

alright >:3

latent latch
#

The documentation is one of unity's best so worth going through it all

#

compared to many other modules unity has released recently

heady iris
#

e.g. the floor

karmic herald
#

cuz i was coming from alteruna and theres little to no docs on that that tell you how to differentiate networked / non networked

#

and i want like. nothing to be networked but the players

crisp bronze
#

What would be a good free alternative that can be used commercially>?

heady iris
#

Ideally you can just figure out how to make it use an installed .NET SDK

#

This was on macOS, so i would not be surprised if it behaves a little better on windows

#

You can find out if this is happening by looking in the Output window

#

I forget exactly which channel you need (ideally there's one called ".net runtime install tool" or something like that)

#

it should say that it's trying to acquire the SDK

chilly surge
rough sorrel
#

Hi. Does anyone know if it's possible to create a replay system that also records the different methods please? Like I know how to make a replay system that records positions and rotations, but then when it comes to recording methods like for example saying when an object has to play a particle system, I am lost

plucky inlet
# rough sorrel Hi. Does anyone know if it's possible to create a replay system that also record...

There is none out of the box track everything system, as you seem to ask for. You should carefully write down, what you want to rewind/replay and then make your code "trackable" for a system. If youw ant to replay all things, you gotta track all things which might result in a very complex system. so maybe track down first, what things you really need to replay and what does not have to be tracked at all

rough sorrel
#

but like how do I "track" it?

#

like a position can be saved each fixed update, but for example a particle system playing or not, would be a waste just saving every fixed update wether it is playing or not

plucky inlet
#

Think of it as an animation clip. At a specific time, a specific state is set.

#

You could even try to "abuse" the animationclip class and add keyframes to it which trigger those methods you are passing in

#

Also timelines might be the closest to what you are trying to do, maybe those can be created and modified at runtime

rough sorrel
#

oh okay. I didn't know that was a thing lol

#

thanks

west lotus
#

Actually the proper way to do a replay system is to record player input and let the game playitself

#

The only problem is unity’s non deterministic physics, so the pos, rots of rb’s can be recorded, quantized and played back

vapid apex
#

Let's say I have a Tree prefab, which every tree uses. And a ScriptableObject TreeData which defines the tree's properties, including its sprite.
Now, when I load my game I can spawn tree's and set their materials texture to the sprite.
But, what if I want to place tree's via editor? I could just place the tree prefabs all over the scene and assign the TreeData reference per instance. But this will only update the sprite in the material in Play Mode. Is there a way, so that when I assign a TreeData object to one of the placed Prefabs, that it automatically updates the texture in the material?
Other option would be having a material variant/prefab per tree, but I don't really want a prefab/material per tree.
Also I'd kinda like to set the tree size in the TreeData object too, so it should also automatically update the scale.

sonic swan
#

I have an issue. I wanto add items to a list in a specific index however when I use list.insert more that once it adds more indeces instead of changing the one assigned to it.

eager tundra
sonic swan
#

thanks

#

it still happens

#

the liost keeps adding new indexes wih the same attached gameobject

#

heres my code

#

snippet

knotty sun
#

and the en.Insert ?

sonic swan
#

same issue

knotty sun
#

show the code for it

sonic swan
#

this is with en[i]

#

i remains 0 throughout btw

vestal arch
#

what exactly are you trying to get? overriding the existing elements, or adding new ones between the existing elements?

#

with the former you would assign, with the latter you would insert

sonic swan
#

so at first inserting elemnts but overriding when the player triggers it again

knotty sun
#

why is en a List and not an Array set to colliders.Length?

sonic swan
#

i tried that but it says arrays cannot be written to

knotty sun
#

of course they can

sonic swan
knotty sun
#

EnemyAI[] en = new EnemyAI[colliders.Length]

cosmic rain
#

You can't modify the length of an array

vestal arch
#

array lengths can't be written to

sonic swan
#

i get your code and it makes sense

#

but it doesnt work

cosmic rain
sonic swan
#

en[i]=colliders[i].GetComponent<EnemyAI>();

cosmic rain
knotty sun
cosmic rain
knotty sun
#

so you make a LOCAL array called en ?

sonic swan
#

yes

knotty sun
#

dont

cosmic rain
# sonic swan yes

Well, then the new array is not gonna contain anything you added to the old array.

knotty sun
#

serious lack of basic C# knowledge here

sonic swan
#

ive never dealt with arrays before

cosmic rain
#

That's basically the same as saying that you never dealt with C# before. Or programming in general.

knotty sun
#

this is not an array thing, it's a question of scope

cosmic rain
#

Anyways, move to #💻┃code-beginner and share the whole code. Also maybe go over the C# basics or the beginner pathways on unity !learn:

tawny elkBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

sonic swan
#

ok

open plover
#

For a mobile game where the score matters, would making a class in which there is an offset and the actual value to create a simple anticheat prevent anything? Should I even bother doing something like this

late lion
open plover
#

I ofc dont want players editing using memory editing programs, and I dont know if other casual mobile games where you upload the score got an anticheat

swift falcon
open plover
late lion
# open plover So I shouldnt bother adding an anticheat since those who are gonna cheat will fi...

It's true that it's impossible to make it 100% cheat proof unless you run everything on a trusted server.

But I would still argue that adding some checks can be worth it. The vast majority of cheaters are going to be using the same popular tool or method to do it, CheatEngine for PC, whatever the equivalent is for Android.

If you are able to add checks that make using those popular tools more difficult, you'll fend off >90% of attempts.

open plover
late lion
# open plover Ty, I’ll see what I can do . Btw Do you know if big hypercasual games (like Stac...

I believe big apps use Google Play Integrity, as a way to check if the app is genuine, unmodified and running on stock firmware, no root, etc.
https://developer.android.com/google/play/integrity

Android Developers

The Play Integrity API helps protect your apps and games from potentially risky and fraudulent interactions, allowing you to respond with appropriate actions to reduce attacks and abuse such as fraud, cheating, and unauthorized access.

#

As far as I know, this system hasn't been broken, at least not trivially enough for average gamers to be able to do it.

open plover
swift falcon
#

Bypassing the need to cheat in your game, making anti cheat useless to prevent that.

open plover
#

Yea but pretty sure google play games and game center block that

knotty sun
#

do not cross post

thin aurora
late lion
thin aurora
#

I was wondering why I could not find where a List does this, but now I see that the list calls EnsureCapacity which ends up calling Capacity which just allocates a new array. 😄

rigid island
#

stick to one channel ?
also you can use the A* project or try the 2Dnavmesh by h8man

wheat spruce
#

speaking of lists, I wonder why microsoft have never introduced the ability to let you modify lists during enumeration.
default behaviour is its not possible to loop over a list and then do .add() or .remove() to the same list without it usually throwing an error

dusk apex
rigid island
wheat spruce
little meadow
#

This is copying the list... mixed feelings... could be useful, but definitely not something I'd use as a List replacement

wheat spruce
#

Ive written similar approaches to the problem before, just having a temporary list that can get written too, so the original doesnt cause problems when you add/remove from it

dusk apex
#

Just iterate the list using one of the other more appropriate means.

little meadow
#

or do .ToList() if you really want a copy 😄

wheat spruce
#

its helpful in very specific situations where I know ahead of time I'm going to be modifying the lists at the same time I need to loop through it. Whether I should have gotten into needing such a thing in the first place, I cant say. But as a quick solution, it does its job

dusk apex
#

Why not just use a regular for loop?

little meadow
#

For loop is not always a good idea... it's kinda random how it will behave with the changes (maybe you removed something before the current item, so effectively you're gonna skip one that's in the list)

dusk apex
#

You'd just have to accommodate for the element removed.

little meadow
#

you can't, you're not the one removing it

knotty sun
dusk apex
#

We're referring to a regular for loop right?

little meadow
#

otherwise sure, you'd just manage the for loop properly

wheat spruce
#

I'm sure ive encountered issues of modifying a list regardless of whether its in a foreach or for loop

#

I know foreach breaks the moment the size of the list changes

dusk apex
#

It doesn't break. It's being used incorrectly and simply informing the user.

ionic grove
#

Do you guys know why my Visual Studio is making my code look faded in some spots. It's not like I'm not using my Update method..

#

But it's telling me I'm not

dusk apex
wheat spruce
ionic grove
wheat spruce
#

but if you used the SafeList in a foreach loop, that does allow you to alter the size of your list without it producing an error, its designed to do that

dusk apex
#

I would just use a while or regular for loop if I'm wanting to modify the list.

wheat spruce
#

I'm not at my PC so I cant check, but wouldnt it break if I modified the lists length during for (int i = 0; i < myList.count; i++){} ?

dusk apex
#

There are no constraints (promises made unlike with for each) with a regular for loop

wheat spruce
#

but removing a bunch of items in the loop will throw an index out of range error, the list will have become shorter than when the loop start

little meadow
#

it won't break... all those are perfectly valid to execute at any time no matter if changes happened or not
you could have an issue, if something else modifies the list while you're looping though

dusk apex
knotty sun
#

hmm, RemoveAt

chilly surge
#

If you don't want "removing an item causing you to skip over the next item" then you can i-- after the removal, or alternatively like what others have pointed out before, loop in reverse.

wheat spruce
#

looping in reverse is a pretty good option

dusk apex
#

Or just decrement as you remove elements

wheat spruce
#

but if for whatever need you're going to modify a list during foreach, SafeList does provide a way to do that

#

important question is "why have you gotten yourself to a point where youd have to do it"

chilly surge
#

If you don't care about order, you can also have O(1) removal doing your own loop. I certainly wouldn't bring in that SafeList implementation.

#

More often than "mutate while enumerating a list," I've had a few instances of needing "mutate while enumerating a dictionary."

dusk apex
wheat spruce
#

The actual use of SafeList makes sense in the context of giving an entity a set of Components.
https://github.com/Martenfur/Monofoxe/blob/632ab5593873c0c11f11eeb15c23a6ca911d24ba/Monofoxe/Monofoxe.Engine/EC/Entity.cs#L80
Its not hard to see issues happening if you added or removed a component when the game is running, unless you implemented a "ComponentsToAdd" and "ComponentsToRemove" pair of lists, but ultimately thats basically what SafeList is doing anyway

GitHub

Foxes made Monogame easy. Contribute to Martenfur/Monofoxe development by creating an account on GitHub.

karmic herald
#

after setting up netcode my streamreader is not working; i set the path of the sr explicitly in the start method and it is supposed to read it from the client only. the path ends up giving an error that says its null even though it was set in start, what am i missing?

wheat spruce
#

either way, I think its a pretty neat solution to a fairly niche problem

modern creek
#

Rigidbody doesn't expose an .enabled property, and a quick google says that if I want to disable physics, I set isKinematic = false on it. How can I do the same for collisions..? I am wanting to make my enemy "gibs" just float through the world after some amount of time, but I can't seem to turn off the collision physics

#

Oh... wait, I see that I have colliders on the children under the parent that I was disabling (that I didn't disable)

modern creek
#

so if I have a parent with an RB and 3 children with box colliders, turning off detectCollisions on the parent is the way to go? or do I disable all the colliders

late lion
#

They should both have the same effect.

modern creek
#

def just turning off the RB on the parent so I don't have to iterate through the trees.. thanks, trying it out now

#

er, turning off collisions on the parent, I mean

vast patio
#

Does anyone know what I have to look for when I wanna auto format my C# code and enforce code styles like private vars prefixed with _?
Wanna use VSCode with unity 6

modern creek
#

The advice you're gonna get here is to use VS (over VSC) because the support/integration is so much better and doesn't require a lot of effort

vast patio
modern creek
#

Ah, yeah.. if on mac, try rider. I'm not an expert in it.. just barely enough to get an app compiled and published to apple, but I do my daily driving on windows + VS. I certainly don't know how to do code styles and linters with rider (or VSC)

eager tundra
#

rider is definitely the way to go on mac

leaden ice
#

has much better C# formatting settings too

late lion
# wheat spruce either way, I think its a pretty neat solution to a fairly niche problem

I had an idea for another way to achieve the same thing without any additional allocation.
https://paste.ofcode.org/3bUZTWwBx7eBRHVkFK9Juch

var list = new List<string> { "Hello", "World", "How", "Are", "You", "?" };
        
var modifier = new ListModifier<string>(list, stackalloc int[1]);
foreach (var (index, item) in modifier)
{
    Console.WriteLine(item);
    
    var indexOfChar = item.IndexOf('o');
    if (indexOfChar >= 0)
    {
        modifier.Insert(index + 1, new string(' ', indexOfChar) + '^');
    }
}

prints:

Hello
    ^
World
 ^
How
 ^
Are
You
 ^
?
gleaming orbit
#

i have an enemy follow player script which tells the enemy to follow player and i also have an enemy spawn script and im spawning in enemy prefabs, how do i set the player trasform(in the scene) to the script in my enemy prefab (in assets)

late lion
leaden ice
#

e.g.

public EnemyController enemyPrefab; // assign to the enemy prefab
public Transform player; // assign in the inspector to the player in the scene

void SpawnEnemy() {
  EnemyController newEnemy = Instantiate(enemyPrefab);
  newEnemy.target = player;
}```
gleaming orbit
#

thanks

heady iris
gleaming orbit
heady iris
#

same problem you have -- Visual Studio on mac was always uh

#

"the visual studio we have at home"

#

and now it's gone

leaden ice
heady iris
wheat spruce
#

C# is a fun language to write in

heady iris
#
// uninitialized spans can't be assigned to later
Span<Vector3> samplePositions = stackalloc Vector3[1];

if (whatever)
{
    samplePositions = stackalloc Vector3[3];
}
else
{

}
heady iris
heady iris
#

(i also assign some actual positions in the if block)

little meadow
heady iris
#

i probably shouldn't have deleted all of the context

wheat spruce
#

I wrote this for a project thats on hiatus, I like the way you can achieve things in a number of ways with it

[Flags]
public enum RopeTypeFlags {
    Rigid = 0,
    Soft = 1
}

public class HalliardMaterial {
    public Dictionary<string, object> Properties { get; private set; }

    public HalliardMaterial(
        Dictionary<string, object> defaultProperties,
        RopeTypeFlags ropeTypeFlag) { 

        Properties = new Dictionary<string, object>
        {
            { "DotCommon", new DotCommon() },
            { "RopeCommon", new RopeCommon() },
            { "SegmentCommon", new SegmentCommon() },
        };

        foreach(var kvp in defaultProperties) {
            Properties[kvp.Key] = kvp.Value;
        }

        Properties["RopeType"] = ropeTypeFlag;
    }
}```
#

would be nice if I could find a way to reuse this snippet in my zen garden project, I like the purpose of HalliardMaterial. I could see it being helpful again

gleaming orbit
leaden ice
#

EnemyController newEnemy
This creates a variable called newEnemy

#

so I'm not sure what your question is

gleaming orbit
gleaming orbit
#

wat do u think i do wrong? @leaden ice

naive swallow
naive swallow
gleaming orbit
#

will this way ruin my performance?

#

@naive swallow

naive swallow
#

When does this run

gleaming orbit
#

@naive swallow

naive swallow
#

Yes, absolutely

#

Don't use Find if you can avoid it, and never ever use it in Update

gleaming orbit
naive swallow
#

Do you expect the object to change at all

gleaming orbit
naive swallow
#

Then why would you reset it every frame

gleaming orbit
short quiver
#

This might be a long shot, but is there a way for me to load a prefab with a Type as a field? As a matter of usecase: my game has an abstract class representing a state in a player character's Finite State Machine, and in the prefab for a given character, I want to map the character's States to the animations I want the model to use in those states. I know that Unity doesn't natively support dictionary fields for prefabs, so I'm thinking to just make an array as follows, and create the map on Awake:

[Serializable]
public class AnimationStatePair {
    public Type type;
    public AnimationClip animation;
}

// ...
public class AnimationStateController : MonoBehaviour
{
    public AnimationStatePair[] stateAnimationPairs;
  // ...
}

Before anybody asks: I don't want to use Unity's built-in animator because it's a pain to duplicate my character's FSM states in the animator. I just want to read the character's State on an Update call and have the game specify their animation state according to the mapping.
If I can't get the prefab to hold the Type in the double, I might use a string to represent the relevant class, but that'll definitely be error-prone

latent latch
#

Are you asking if it's serializable in the editor? Doubtful the editor hates ambiguous types first off

#

But yes, making an array then initializing it into a dictionary is one way around that problem

heady iris
#

Perhaps this is a place to use SerializeReference

#

but I'm not sure

#

ah, no, not really -- you'd use that to serialize the entire State

little meadow
gritty badger
#

Need a ltiile help here'.
So the black rectangle is a gun, and it should facing and plays the animations paralell with the player, not perpendicular.
I tried flippijng the animation but for a short second it works and then It becomes this:

#

code:

    public void grab(Transform _parent){

        weaponphys.linearVelocity=Vector2.zero;
        knife.transform.SetParent(_parent);
        // knife.transform.position=new Vector2(_parent.transform.position.x,_parent.transform.position.y-1);
        if(_parent.tag=="weaponholdpos"){
            
            PivotTo(_parent.transform.position);
            // knife.transform.rotation=_parent.transform.rotation;
            // only for melee-|
            Debug.Log(knife.transform.rotation);
            // knife.transform.rotation=quaternion.Euler(_parent.transform.eulerAngles.x,_parent.transform.eulerAngles.y,_parent.transform.eulerAngles.z+90);
        }
        // if(_parent.tag=="npc"){t.position.y));
        // }
        //     PivotTo(new Vector3(_parent.position.x+1.5f,_paren
        canpick=false;
        anim.SetBool("picked",true);
        anim.SetBool("attack",false);
    }
short quiver
gritty badger
#

anyone?

mental reef
naive swallow
mental reef
dusk apex
timber zealot
#

guyss

#

can anyone heIp?

#

i dont know how to open script in unity

#

@dusk apex

#

bruh no one is online

#

@mental reef

mental reef
#

Why are you pinging me Shiba_Cry

timber zealot
#

cuz i need help

#

how do i open scripts?

mental reef
timber zealot
#

no

#

im new

#

im using chatgpt

#

to create scripts for me

#

but idk how to create script

mental reef
#

I'd recommend learning the basics. If you haven't even searched up how to create a script. I don't think game dev is for you. It's like the first thing every tutorial teaches you first 😭

sleek bough
#

@timber zealot Don't ping people not in conversation with you. And start here Unity !Learn

tawny elkBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

timber zealot
#

750 HOURS?!?!?!?!?

mental reef
timber zealot
#

well chatpgt gonna carry me

mental reef
#

Good luck

timber zealot
sleek bough
timber zealot
sleek bough
sleek bough
timber zealot
#

bro no one is in code beginner

#

all npcs

timber zealot
sleek bough
#

@timber zealot If you won't stop spamming I'll just mute you.

timber zealot
#

im tyiping like a normal human

sleek bough
#

!mute 979824243913130004 1d Ignoring warnings, spam

tawny elkBOT
#

dynoSuccess realawok was muted.

mental reef
#

😂

sleek bough
#

Find methods useful for debugging or when you don't have control of the code to get it properly.

mental reef
cosmic rain
mental reef
#

So would GameObject.Find("name") and FindAnyObjectByType both be classed as the sameish function? They both look for whatever they need to and fill in the empty slot? So try and avoid using any Find function or is it purely GameObject.Find? Reason I'm asking is because apparently GameObject.FindWithTag is faster and is a preferred alternative. Hopefully I make sense

cosmic rain
mental reef
latent latch
# mental reef So would GameObject.Find("name") and FindAnyObjectByType both be classed as the ...

If you need specific references from the scene, usually you can resolve a lot of that at editor time by binding those references directly on the UI. Now, if there are objects that are instantiated after the scene is loaded, you may not have those explicit references bound. Ideally when you do create these objects, you do pass on those references to that newly created object.

Though, sometimes you may not have those references available to pass onto it, or perhaps this reference you want is so common it seems silly to bind to every object. This is where Singletons come in, they basically replace the need for a lot of these Find/Search methods by having a global/static reference you can call where ever in your script, as long as this class instance exists in the scene.

mental reef
#

I'm currently looking at dependency injection and tweaking some code

mental reef
#

Right. I feel like my brain is melting but this is what I have...

#

This is my Dependency class

#

something like this? I'm aware it probably is butchered

sleek bough
#

You've been on the right path. You don't need singletons it will make it harder to debug problems.

#

Just pass reference and use it

#

Singleton used to expose public variable globally everywhere. Having such a large scope you might run into problems figuring out what exactly changed it and when. While proper references with limited scope will point to a problem right away. That just one of the problems with it.

mental reef
#

I think I might work on something else just for now. my brain is mush and I don't want to burn myself out. Atleast I'm learning something new and this is something that'll help a lot with managing code

sleek bough
#

Just compartmentalise problems and solve them bit by bit. Don't have to overwhelm yourself.

sleek bough
gleaming orbit
#

hii guys my visual studio doesnt work properly like the little tool that finishes the words for u has very limited things and things like the character controller arent green , does anyone know wats the problem is? (i dont know how to explain it better)

vestal arch
#

!ide

tawny elkBOT
sleek bough
sleek bough
mental reef
# sleek bough Just pass reference and use it

So I'm spawning in enemies. They need to have access to the player to movetowards and the spawner. So I should get access to my Dependency class from my enemy controller somehow and then access the method I made in the script I shared?

sleek bough
#

enemy = Instantiate(enemy);
enemy.AssignPlayerReference(player);

#

can even inline it
enemy = Instantiate<EnemyClass>(enemy).AssignPlayerReference(player);

mental reef
sleek bough
#

Then enemy will have player class instance reference as "injected dependency" for future use.

#

You might want to pass stats keeping object here as well so enemy can pass values to that reference as well

#

Similarly pass score board reference to player as well so they can enumerate score when done something.

vestal arch
sleek bough
vestal arch
#

as in, enemy would just be the component?

sleek bough
#

You can reference prefabs as type directly as well

vestal arch
#

oh, does it instantiate the gameobject attached to the component?

#

i was under the assumption it'd just instantiate the component itself

sleek bough
#

Enemy enemyPrefab;
You can instantiate that directly.

#

As long as it's inheriting MonoBehaviour

vestal arch
#

but it does create the full gameobject, correct?

sleek bough
#

MB can't exist without being also a GameObject

#

Or rather also having GO and Transform

vestal arch
#

isn't that a "has" relation rather than an "is" relation

hexed pecan
#

Your name really checks out

sleek bough
#

Prefab itself can't exist without being an asset with GO setup already. If you doing things purely from code then you add script to an empty GO, for example.

vestal arch
#

im not questioning that

fiery mountain
#

guys is there anyone that can help me with my multiplayer game

#

i have a set of code that doesnt work on client

#

but it works perfectly on host

cosmic rain
daring pine
#

Hello so ive been meaning to make a script that detects that if this box is triggired It will go to this scene and enable and desable that

#

how do i do that

#

no

#

ik that

#

i want it to work from scene 1 to change something in scene 2

prime quarry
#

Hi my raycast keeps colliding with the npc running this codes own collider, issue is i cant remove the collider or filter it out by layer because it needs to detect the colliders of other npcs, just not its own. I am really struggling to find a way past this issue, any help will be much appreciated.

     private bool IsInLineOfSight(Character character)
    {
       
        var ourPosition = _npc.GetPosition();
        var targetPosition = character.GetPosition();
        if (Vector3.Distance(ourPosition, targetPosition) > _detectionRadius)
        { return false; }

        var dirToTarget = (targetPosition - ourPosition).normalized;

        if (Vector3.Angle(_lookDirection, dirToTarget) > _viewAngle / 2f)
        { return false; }

        var raycastHit2D = Physics2D.Raycast(ourPosition, dirToTarget, _detectionRadius);

        if (raycastHit2D.collider != null && raycastHit2D.collider.gameObject == character.gameObject)
        { return true; }


        return false;
    }
daring pine
#

no

#

i want something to change something from diffirent scenes

#

let me explain it more

#

so i have a suspecse scene and a box trigger in my main game scene and this trigger ig its triggered it will change to suspense scene (i alr did that) but i also want it to change the main menu load button cause the main game scene will be another scene, because if the players uses the load button it will return to main game scene 1 while i want it to go to main game scene 2 wich is triggered by that box collider, so i want to make a new load button and enable it with the trigger so it can load main game scene 2

#

do u understand me?

#

@severe tinsel

still ermine
daring pine
#

YES

#

so how can i edit the script to do that

#

if i can just make the code change the name in the script it would be easier tbh

#

but i think impossible to do that

#

yep i dont understand it

#

this

#

Wsit

#

how can i store the name in a variable

#

if the scene name is in a script

#

and if the trigger triggers how do i change it if its in another scene

#

WHAT THE HELL IS CROSS POSTING

#

ITS A DMAN CODE

vagrant blade
daring pine
#

OK DAMN

#

im only posting it here

#

damn

#

is there no easy way out of this 😦

#

hey cant a script work by itself, and in the background, imm SURE theres a way

hexed pecan
#

What are you trying to do?

daring pine
# hexed pecan Wdym exactly, like multi threading?

so i have a suspecse scene and a box trigger in my main game scene and this trigger ig its triggered it will change to suspense scene (i alr did that) but i also want it to change the main menu load button cause the main game scene will be another scene, because if the players uses the load button it will return to main game scene 1 while i want it to go to main game scene 2 wich is triggered by that box collider, so i want to make a new load button and enable it with the trigger so it can load main game scene 2
do u understand me?

#

i want the script to check if this triggers, desable this in scene 2 and enable this in scene 2

#

while its working in background between scene 1 and 2

hexed pecan
#

do u understand me?
Barely, but sounds like you just want some sort of way to save/load data

#

Not sure how it's related to the "background script" question, though. Maybe you want DDOL?

daring pine
#

i just want when a trigger triggers it goues to scene 2 and desable and enable this

#

and to save ill use player prefgs

vestal arch
#

what does "disable and enable this" mean

#

what is "this" in that sentence

daring pine
#

A gameobject

#

wia

#

WHAT IF I ADD A CODE IN MAIN GMAE 1

#

THAT IF THE TRIGGER TRIGGERS, IT WILL DO THIS THIS, BUT IF THE PLAYER COMES TO MAIN GAME 1 AGAIN IT WILL REMOTE HIM TO MAIN GAME 2 WITHOUT QUESTION

#

WAIT I CAN ADD A EMPTY GAME OBJECT

hexed pecan
#

Why are you shouting?

daring pine
#

yea an idea just popped

#

so if this game object enables it will load this scene BUT it will always be enabled Cause i will add a Player prefs save so if it loads to this its alr enabled so it takes him or i can make a timeline cutscene thta does that

daring pine
#

"?

hexed pecan
#

What

#

Why do you need a gameobject for this? Can't you just use a saved bool/int?

daring pine
hexed pecan
#

Or do you want it to go to scene 1 first before scene 2?

daring pine
wheat spruce
#

I'm confused on something. If I place these 2 Components in my GameObject, the SimplePlane is responsible for creating a Rectangle struct (just a simple definition for a rectangle, pretty basic), and the PlaneQuad and components like it, make use of the Rectangle and it constructs a new mesh.

The thing I'm confused on is the actual order things execute. Just sticking both components on there before I hit play, means Awake will be called in each, so if PlaneQuad calls before SimplePlane, thats going to cause problems.

#

I get the idea is youre meant to use the inspector to set everything up, but I feel uneasy about that, especially as Unity Components arent really designed to have a constructor, if they did I could easily ensure everything is added and constructed in the correct order

#

I cant imagine a correct thing to do is something like this

public class TerrainCore : MonoBehaviour
{
    SimplePlane Plane;
    [SerializeField] GameObject HandleA, HandleB;
    Rectangle Rectangle => Plane.Rectangle;

    PlaneQuad PlaneQuad;

    void Awake()
    {
        ConstructSimplePlane();
        ConstructPlaneQuad();
    }

    void ConstructSimplePlane()
    {
        Plane = gameObject.AddComponent<SimplePlane>();
        Plane.Construct(HandleA, HandleB);
    }

    void ConstructPlaneQuad()
    {
        PlaneQuad = gameObject.AddComponent<PlaneQuad>();
        PlaneQuad.Construct();
    }
}```
heady iris
#

there are quite a few options here

#

SimplePlane could lazily create its data the first time you access it

#

you could have each component initialize itself in Awake and then access each other in Start

#

More generally, if you have components that depend on each other, you need to either:

  • Ensure that they run in the right order (e.g. Awake, then Start)
  • Explicitly enforce an order by having one component talk to the other (e.g. require that you call an "Init" method on another object before you use it for the first time)
  • Make the order irrelevant (e.g. lazy initialization)
wheat spruce
#

honestly I've gone through a number of options and I just cant settle on anything

#

something about using the editor GUI feels like it adds a whole layer of confusion/complexity than my TerrainCore class, and that really doesnt sound right to me

wheat spruce
#

for instance, I could have TerrainCore contain a child for each component, or I could have TerrainCore be the thing that contains all the components

#

all my instincts and urges are telling me "literally start with an empty gameobject, have TerrainCore be the thing that instances and configures every single thing" and also "avoid using the inspector as much as possible"

#

I think thats only really due to the fact that I've been doing gamedev without access to an editor/GUI, I'm too comfortable working exclusively in code

leaden ice
gleaming orbit
#

hii, where do i put the "if (enemy == null)" in order to avoid the "NullReferenceException: Object reference not set to an instance of an object
PlayerHealth.Update () (at Assets/Player/PlayerHealth/PlayerHealth.cs:20)"?

wheat spruce
#

Youd want if(enemy != null) to confirm that the enemy is not null, that way you wont attempt to do anything with enemy that doesnt exist.

leaden ice
# gleaming orbit

this code doesn't make any sense... what if there are multiple enemies?

#

It's also going to be extremely inefficient

heady iris
#

why is PlayerHealth damaging enemies?

wheat spruce
#

it might make more sense for you to read it as if(enemy is null) or if(enemy is not null) both of which work

heady iris
#

oh, it's taking damage from the enemy

gleaming orbit
heady iris
#

that's a very misleading method name

wheat spruce
#

I find is to be easier to understand as a glance than ==

heady iris
#

Unity objects compare equal to null if they are invalid

leaden ice
heady iris
#

but they aren't actually a null reference

#

This would malfunction here, because many Unity methods give you an invalid object reference (instead of a genuine null) if they fail to find something

wheat spruce
#

huh, I always thought is was identical to ==, just as an extra way to write the same equator

heady iris
#

It explicitly doesn't work! 💥

wheat spruce
#

seemed like it was more of a QoL addition to the language

chilly surge
#

== can be overridden (which Unity actually does), whereas is cannot.

heady iris
#
if (whatever is SpecificThing thingy) {
  thingy.DoThing();
}
#

along with this very neat operation

wheat spruce
# gleaming orbit ty

I redact that post if the others are saying is/is not, is not a good option for Unity

gleaming orbit
heady iris
#

let's first look at why your code is producing errors

#
if (enemy == null) {
  enemy = // something that tries to get an enemy
}

enemy.DoThing();
#

Why is it possible for the last line to produce a null reference exception?

wheat spruce
#

I'd say you need a better solution of how to find your enemies. GameObject.Find does its job, but it does its job pretty ineffectively. Plus it relies on you never having your enemies named anything other than "Enemy(Clone)", so what happens in the future when you decide you want 5 enemy types each with a different name

#

Unsure what that solution might be, but say you had a list of all possible enemies that exist.
Your Update code could instead be written like

void Update
{
  if(enemyList.count == 0) {
    return; //this basically forces Update to exit early, the rest of your Update code wont run
  }
//rest of your code here that will do something with the enemy
//stuff can only run here when the list absolutely has at least 1 enemy
}```
#

Reason specifically why the code here can result in an error later on, is that the code there is basically saying "if the enemy doesnt exist, find the enemy", but nothing actually guarantees those 2 lines will find the enemy. And as your code is designed with the assumption that an enemy will always be found, that can lead to problems

rigid island
#

!code

tawny elkBOT
rigid island
#

!screenshots

tawny elkBOT
#

mad No

Be mindful, if someone requests your code as text, don't send a screenshot!

gleaming orbit
#

@rigid island

rigid island
gleaming orbit
rigid island
#

explain the issue, what is happening, vs what you expect to happen

gleaming orbit
#

i have two scripts, Player health and Enemy Controller, in Player Health i have a method that takes away damage every 5 seconds and in enemy controller the enemy follows the player and if its 5 or under away it stops and im trying to get the Player Health method to work inside the stopping if statement. Can you tell me wat i did wrong?

#

@rigid island

rigid island
gleaming orbit
#

@rigid island this should work

rigid island
gleaming orbit
#

NullReferenceException: Object reference not set to an instance of an object
EnemyController.Update () (at Assets/Enemy/EnemyController.cs:38)

rigid island
#

you cannot run functions on a null object

#

and looking for a PlayerHealth on an enemy controller doesn't make much sense

#

look at these two lines carefully cs target = GameObject.Find("PlayerBody").transform; health = GetComponent<PlayerHealth>();

rigid island
#

first sentence in description is especially important

gleaming orbit
rigid island
gleaming orbit
#

GetComponent<PlayerHealth>().PlayerTakeDamage();

#

do i do this in else statement instead?

#

@rigid island

rigid island
#

you have read the page you said

#

or you just clicked it

gleaming orbit
rigid island
rocky jackal
#

i need the rgb bit for later but why exactly does this load forever with size x and y being 20 ?

rigid island
#

also its literally the first tab..

gleaming orbit
rigid island
# gleaming orbit im sorry for not understanding but wat does" reference to a component of type T ...

btw you should probably do the courses on the unity learn website and start with the pathways
A reference is basically you wanting a specific component and usually doing something with it. Type T meaning it can be whatever type eg class
(Components are the scripts that are on the gameobjects)

#

GetComponent just look for a component you want, in this case PlayerHealth but you are looking for it on whichever gameobject has the EnemyController component.

#

if it belongs on the player/target and you already find the player/target on this line target = GameObject.Find("PlayerBody").transform;
Where do you think you should use GetComponent on instead?

dusk apex
rigid island
#

in particular the second part of the documentation I sent. Should point you to your fix

You can also call this method on a reference to different component, which might be attached to a different GameObject. In this case, the GameObject to which that component is attached is searched. For example:

myResults = otherComponent.GetComponent<ComponentType>()

gleaming orbit
rigid island
#

if you're confused on something specific you should ask

#

your enemy is looking for PlayerHealth on itself, don't do that.
if you need the one on the player, you have to get it from the player which you already in the line i pointed to you

#

if you don't know your own scripts you use, take a step back and learn the essentials

heady iris
#

If you don't understand why this is a problem, you need to immediately stop what you are doing and start following a properly structured tutorial

gleaming orbit
rigid island
cloud osprey
wheat spruce
#

it would be almost instant if you wrote a shader to do it

rocky jackal
wheat spruce
#

ah, gotcha

heady iris
#

Personally, I would make a pool of audio sources and pull them out of the pool each time I need to play a precisely-scheduled sound

#

If you have no warning before the sound is played, you might need to have many more audio sources with the clips already assigned. That's what's described in the thread.

I haven't had to do this before, so I don't know!

cloud osprey
#

i see, i will try to make a prefab with the audiosource and create an instance a little before when I need it played. i'm making a game closely tied to the rhythm so I need the sound to be fairly accurate

ivory spade
#

can someone help

using UnityEngine;
using System.Collections.Generic;

public class SpawnNote : MonoBehaviour {
    [SerializeField] private GameObject BNote, RNote;
    private readonly float[] BNotePos = { -4.866f, -3.59f, -2.450f };
    private readonly float[] RNotePos = { -1.36f, -0.086f, 1.03f };

    private List<GameObject> instantiatedBNotes = new List<GameObject>();
    private List<GameObject> instantiatedRNotes = new List<GameObject>();

    private void Start() {
        GameObject notesParent = new GameObject("Notes Instants");
        GameObject bNotesParent = new GameObject("BNotes");
        GameObject rNotesParent = new GameObject("RNotes");

        bNotesParent.transform.SetParent(notesParent.transform, false);
        rNotesParent.transform.SetParent(notesParent.transform, false);

        for (int i = 0; i < BNotePos.Length; i++) {
            for (int j = 0; j < 10; j++) {
                Vector3 position = new Vector3(BNotePos[i], -2.71f, 27.51f);

                GameObject bNoteInstance = Instantiate(BNote, position, BNote.transform.rotation);
                bNoteInstance.transform.SetParent(bNotesParent.transform, false);
                instantiatedBNotes.Add(bNoteInstance);
            }
        }

        for (int i = 0; i < RNotePos.Length; i++) {
            for (int j = 0; j < 10; j++) {
                Vector3 position = new Vector3(RNotePos[i], -2.71f, 27.51f);

                GameObject rNoteInstance = Instantiate(RNote, position, RNote.transform.rotation);
                rNoteInstance.transform.SetParent(rNotesParent.transform, false);
                instantiatedRNotes.Add(rNoteInstance);
            }
        }
    }
}

while the x values are correct when in gamemode for notes that will be instantiated. But when instantiated, inspector shows same x position but it's offset

#

why?

knotty sun
#

At a guess because you are using SetParent with false

tulip spruce
#

Is it a good idea, for a highscore based singleplayer game, to combine killedEnemyCount with SurvivalTime for one score or to have them as separate scores and then implement another sorting (rank) alogrithm?

tulip spruce
ivory spade
knotty sun
# ivory spade so I should use it with true?

depends. what you are seeing in the inspector is the child objects local position relative to it's immediate parent. It's world position will be dependent on all of it's parents only you can decide what it is you actually want

ivory spade
knotty sun
#

then you need to start debugging which is what you should have done before coming here.
I suggest logging both of the objects world and local positions before and after the calls to SetParent

rocky jackal
#

how can i make unitys perlin noise look like blenders default noise texture ?

rocky jackal
leaden ice
#

the only real things you do generally are scaling it and translating it

rocky jackal
leaden ice
#

You could run it through some functions though

#

to modify it as you wish

rocky jackal
#

i think ill have to implement my own fBM noise to get the same results

leaden ice
rocky jackal
#

its Fractal Brownian Motion or fractal noise it uses sins in different frequencies and stuff idk how perlin noise is generated

leaden ice
#

yeah it's different

cold parrot
#

brownian motion means that the values change gradually

rocky jackal
cold parrot
#

You can construct blender’s fbm from unity’s Mathf.Perlin

rocky jackal
rocky jackal
cold parrot
#
float fbm( in vecN x, in float H )
{    
    float t = 0.0;
    for( int i=0; i<numOctaves; i++ )
    {
        float f = pow( 2.0, float(i) );
        float a = pow( f, -H );
        t += a*noise(f*x);
    }
    return t;
}
cold parrot
#

The noise() in the above code can be any gradient noise, including perlin

#

for it to be fractal, the octave count needs to be infinite, which it can only be in theory

rocky jackal
#

but with the blender node my noise octaves are set to 1

#

and it looks like this

cold parrot
#

fbm with octaves = 1 is just the source noise

rocky jackal
#

then why does it look so different

cold parrot
#

it’s normalized

rocky jackal
#

isnt unitys perlin noise aswell ?

cold parrot
#

Possibly has a different gamma than unity‘s, potentially uses simplex noise

#

maybe it’s just rendered differently in the preview

#

I would say it looks the same aside from the tonemapping fo the values

rocky jackal
#

Heres with bw seperation at a value of .5 you can see its not the preview that makes it look different, they dont have the same distribution

#

the blender one now has more black and unity is perfectly equal

cold parrot
#

As I said, different tone/value mapping, structurally still the same

leaden ice
cold parrot
#

Actually looks like octaves 1 in blender is two equally weighted perlin samples combined

#

In any case fbm is fbm, any difference is in the used noise function

#

perlin has a more efficient alternative: simplex noise

#

(No idea if blender/unity’s perlin is original perlin or simplex)

prime quarry
#

Hi my raycast keeps colliding with the npc running this code, own collider.
Issue is i cant remove the collider or filter it out by layer because it needs to detect the colliders of other npcs, just not its own.
I am really struggling to find a way past this issue, any help will be much appreciated.

     private bool IsInLineOfSight(Character character)
    {
       
        var ourPosition = _npc.GetPosition();
        var targetPosition = character.GetPosition();
        if (Vector3.Distance(ourPosition, targetPosition) > _detectionRadius)
        { return false; }

        var dirToTarget = (targetPosition - ourPosition).normalized;

        if (Vector3.Angle(_lookDirection, dirToTarget) > _viewAngle / 2f)
        { return false; }

        var raycastHit2D = Physics2D.Raycast(ourPosition, dirToTarget, _detectionRadius);

        if (raycastHit2D.collider != null && raycastHit2D.collider.gameObject == character.gameObject)
        { return true; }


        return false;
    }```
thick terrace
prime quarry
thick terrace
#

no, but you can order the results by distance

#

the distance property of RaycastHit, i mean

leaden ice
prime quarry
#

oh snap thats a good point

prime quarry
leaden ice
#
int oldLayer = myObj.layer;
myObj.layer = Physics2D.IgnoreRaycastLayer; // or any layer that's not included in the layer mask
var raycastHit2D = Physics2D.Raycast(ourPosition, dirToTarget, _detectionRadius);

myObj.layer = oldLayer;```
#

for example

prime quarry
#

thank you

fringe dagger
#

Hello, quick question that I couldn't find an answer to online. Is it possible to have a generic params argument for a function that accepts any type, then I just cast the type later on. An example:

    public void SetState(params any[] settings)
    {
        duration = settings[0] as float;
        animator.Play(settings[1] as AnimationClip);
    }

knotty sun
#

object[] but it will box/unbox primitives if you use them

fringe dagger
knotty sun
#

will all the params be the same type in any one call

rigid island
fringe dagger
fringe dagger
knotty sun
#

so
void SetState<T>(params T[] settings) { }
wont work for you>

hexed pecan
#

Could make T an interface for struct wrappers

#

Or would that also box

fringe dagger
knotty sun
#

SetState<int>(1,2,3,4)

fringe dagger
#

Ah I guess thats only for a single type, so yea that wont work

hexed pecan
#

How would this SetState method be used?

knotty sun
#

I can only think of an interface wrapper as mentioned above

#

should not box

#

nasty though, bad code smell

thick terrace
knotty sun
#

ouch

thick terrace
#

you see that used in stuff like logging frameworks sometimes, some of them use codegen to generate overloads with up to like 32 generic params

knotty sun
#

the IL that must generate does not bear thinking about

fringe dagger
#

Heres a quick example of what I have vs what I'm trying. Doesn't seem possible, which is okay since my current method works.

public class Entity 
{
    public AnimationClip StunAnimation;
    
    public void StunEntity(float duration)
    {
        stunDuration = duration;
        ActiveState = StunState;        

        //ActiveState.StartState(this);
        //ActiveState.StartState(this, duration, StunAnimation);
    }    
}


//V1: Current method
public class StunState : State
{
    private float stunDuration;
    
    public override void StartState(Entity owner)
    {        
        stunDuration = owner.GetStunDuration();    //Cached value I made before setting the state
        SetAnimation(owner.GetStunAnimation());
    }
}

//V2
public class StunState : State
{
    private float stunDuration;
    
    public override void StartState(Entity owner, params any[] settings)
    {
        stunDuration = settings[0] as int;
        SetAnimation(settings[1] as AnimationClip);
    }
}
leaden ice
#

but there are better ways

fringe dagger
#

This codes gonna get called ALOT, nearly everytime an Entity is damaged so I might be better off just doing what I have now

vital oracle
#

When extending a script how do you handle the order of variables, mostly for serialized in the inspector?

Say for instance I have a script with headers for each section of serialized variables. How can I control where in the stack the new variables in the extended script within the header?
I can't figure out how to have them not always show at the bottom of the stack.

leaden ice
vital oracle
glass rivet
#

Does anyone know how to make only the tiles from a tileset turn transparent when the player is behind them? I want to ensure that only the specific walls obstructing the player's view become transparent, not the entire tileset.

fast dune
#

Should I use StringBuilder over normal string concatenation?

  • The amount of nodes in the tree is unknown
      private static void GenerateUniqueNames(Transform rootNode)
        {

            void SetUniqueNameForNode(Transform node)
            {
                // GetInstanceID returns a unique ID for every GameObject during a runtime session
                node.name += " uid: " + node.gameObject.GetInstanceID();
                
                foreach (Transform child in node)
                {
                    SetUniqueNameForNode(child);
                }
            }

            foreach (Transform child in rootNode)
            {
                SetUniqueNameForNode(child);
            }
        }
cold parrot
silver hatch
#

I have a question about architecture/design. If I want to make an item system like risk of rain 2, what would be a good way to implement is so I don't have to make a script for every single item?

#

I'm thinking a class with an enum for every item name then I select it in the inspector, but that feels kinda cheap. I'm wanting to code more professionally

cold parrot
cold parrot
# silver hatch I'm thinking a class with an enum for every item name then I select it in the in...

the "professional" approach is (as dumb as it sounds) to have as few types (classes) as possible and implement items as configurations of the same type as much as possible, this ties in with the type-object pattern above. Try to use composition over inheritance, in practice, one abstract base class and interfaces are OK. Resist OOP thinking and breaking stuff down into an inheritance hierarchy.

tacit bay
#

What channel can I ask for animation help in?

#

Found it, sorry

silver hatch
cold parrot
#

it also helps thinking about how you want to implement upgrades, saving/restoring game state, unlocks, buffs, debuffs, trading items, representation in ui/shop/world/preview. you will notice, integrating all that with "each item is a class" gets extremely tedious and error prone

cold parrot
#

Modular components usually lead to "programming" gameplay in the editor via component configuration, you want to avoid that at all cost in production, but have it in prototyping

silver hatch
#

Yes, but even if I have a base item class for common methods, I'd still need to make a script for every item since they each do something unique right?

cold parrot
#

modularity should exist on a systems level, each system should exist independent of most others and fit into a clear dependency hierarchy, putting everything in assemblies (asmdefs) helps with enforcing a clean hierarchy (don't make those systems too small though, its annoying to deal with 100s of asmdefs)

cold parrot
#

usually items aren't really that unique

#

i understand items to mostly be things that act directly as modifiers/triggers of the games rules.

#

you can think of most things that game rules do as modifying counts of items in lists, and your item features are just rules for how that happens, most of them are functionally identical and only flavoured, again, by type objects

silver hatch
#

I'm thinking I'll have a base class for items then 2 child classes for ones that change stats and ones that have unique abilities. Then just use an enum for assigning them in the inspector.

#

Thank you this was very helpful

spare dome
cold parrot
#

whats confusing about that?

tropic wing
#

I got a kinda specific problem, I'm currently working on a chunk system and everything works so far except for the rule tiles being used on those. Since every chunk has it's own Tilemap but using the same grid those connecting rule tiles obviously are not connecting due to the connecting neighbor being on another tilemap. Thought I could handle this through a custom rule tile but apparently you cannot get the absolute tile position so I could calculate the corresponding chunk to check it's tile. Anyone got an idea for this? Hmm

(I did a workaround custom setting the tiles for all possibilities through code instead of just setting the rule tile, but that makes the code weird, so if anyone got an idea I'm down)

compact spire
#

Runtime modification of meshes (merging/splitting meshes) would be a difficult challenge would it not?

heady iris
#

My last shot at an inventory system had just "melee weapon", "ranged weapon", and "consumable". This still caused lots of annoying if (item is InventoryMeleeWeapon weapon) conversions

steady moat
heady iris
#

yes, that is the thing i've noticed when taking that to the extreme

#

now I just have Blobs

#

everything is Blob

#

Blob can't do anything

steady moat
#

My biggest issue is making the configuration configurable. If you know what I mean. You have something like a "DealDamageEffect" that triggers on X events, but you need to feed its target and its damage

heady iris
#

Yeah

steady moat
#

The damage is then a composition of multiple factor, such as the AttackPower of your target, but maybe also the power level of the current ability, etc.

heady iris
#

One ideal I've poked at a few times is having nothing be "hard coded" at all

#

e.g. an entity does not have to have a health value

#

some do, some don't

#

I feel like I'm trying to make a bootleg ECS

steady moat
#

You either make statistics by composition or make them by type.

#

Both have their issues.

#

At the moment, I'm running with fully composition for pretty much everything.

#

It does not really work that well to be honest.

heady iris
#

uh oh, string keys

steady moat
#

You cannot get aways from that.

#

But thoses are statistics that are referenced only in the modifier

#

Otherwise, I do use StatisticDefinition.

heady iris
#

This is a "Precept", which is used to generate goals for my AI to try to achieve. It states that it wishes to perform an action that achieves the "Avoided" state with another entity, based on a set of scorers that weight the value of achieving that state

#

I'm actually kind of happy with how this has been working out

steady moat
#

But the issue, is that I cannot set the StatsticDefinition to be of Damage for this Modifier, because it is not the damage of this particular modifier but the damage of the modifier it is going to apply.

heady iris
#

although, this part is hard-coded to expect that I have a "friendliness" relationship and a "threat" relationship. I should replace this with a list of Relationship objects and corresponding curves. oops.

steady moat
heady iris
#

There's no point in trying to make something that's so flexible that it can do anything

#

Because, by definition, you've just recreated a programming language

#

Just write the code at that point!

steady moat
heady iris
#

A happy medium might be to implement commonly-used thingsd as configurable behaviors

steady moat
fallen lotus
#

Does anyone know why previous scene is bleeding into the background when I call SceneManager.LoadScene()?

private void TurnPage()
    {
        if (currentIndex < (cutsceneFrames.Count - 1))
        {
            currentIndex++;
            SwitchSprite();
            SwitchText();
        } else {
            SceneManager.LoadScene(2);
        }
    }

This is the method that gets called when you click the button. since it is the last frame of the cutscene, it does the else and transitions you.

cosmic rain
fallen lotus
#

This is the new scene

#

This is the old scene

cosmic rain
#

Just to make sure it's not a render target clearing issue

fallen lotus
#

Switched the new one to this

#

wait

#

yeah still doing the same thing

fallen lotus
#

pet store scene is now this

fallen lotus
cosmic rain
#

Since the second camera viewport width is smaller, it doesn't render or clear the areas that were previously rendered to by the first camera.

fallen lotus
cosmic rain
fallen lotus
#

That fixed it! i wonder why that got changed 😂

#

Thanks for your help @cosmic rain!

solemn ember
#

hello gang

#
[System.Serializable]
public struct DeckData
{
    public string DeckName;
    public string Deckscription;
    public int LeaderID;
    public List<string> CardIds;
    public string Filename;
}

Would I have any trouble putting this in a... formatted file?

#

like those unreadable game files, idk what they're called

latent latch
#

Json

#

oh unless you want binary

solemn ember
#

Json? you can open that with a notepad

#

yeah, something to make it hard for people to modify

latent latch
#

Json is preferable because it's humanreadable ;)

solemn ember
#

well right now I use Json and save it as .JaroDeck

#

which is super nice

#

but I don't want it to be readable

#

so you said binary?

latent latch
#

I'd read over BinaryFormatter. I was going to suggest it just to wade out people who do want to modify the data, but seems like people run into other issues with it

#

it's not secure in any case

lean sail
#

binary writer is better, binaryformatter isnt secure

solemn ember
#

^ oh cool

#

I just don't want to make it super easy

#

to cheat

#

yesss this is perfect

open plover
#

I have a 2d sprite in my world space. How can I make it so that an image in my canvas matches the sprite both in size and position?

broken flume
#

why does it not let me export?

wraith spear
#

I'm having some trouble with Buttons.
I've set up a Button with Transition- Sprite Swap and a specific Highlighted Sprite. However, when I click the button, the highlight is removed until I move my mouse away from the button. I want it to always highlight as long as the mouse is hovering over it;.
Based on some searching, I've tried setting the Navigation to None and the Selected Sprite to the standard sprite, but it doesn't work yet (button not highlighted post-click). Anyone knows a solution?

pine carbon
#
private void Start()
    {
        Debug.Log(texture.format);
        output = new Texture2D(texture.width, texture.height, TextureFormat.ARGB32, false);
        Camera cam = Camera.main;
        cam.clearFlags = CameraClearFlags.Color;
        cam.Render();
        RenderTexture.active = texture;

        output.ReadPixels(new Rect(0, 0, output.width, output.height), 0, 0);
        output.Apply();

        AssetDatabase.CreateAsset(output, "Assets/IconGenerator/output.asset");
        Sprite sprite = Sprite.Create(output, new Rect(0, 0, output.width, output.height), new Vector2(0.5f, 0.5f), 100);
        AssetDatabase.CreateAsset(sprite, "Assets/IconGenerator/sprite.asset");
        
    }
#

Why are they different even tho i copy one from other

#

😭

cosmic rain
#

Or vice versa, the sprite asset that you create should not be srgb.

#

Depending on which one is supposed to be correct.

pine carbon
#

İ set both render texture and the outputs format to ARGB32

cosmic rain
#

Take a screenshot of the texture asset that the sprite belongs to.

cosmic rain
pine carbon
cosmic rain
pine carbon
#

İ managed to save it as a png and it works but when i convert it to a sprite its srgb again

#

Ok i fized that too ty

cold parrot
# heady iris This is what I’ve been moving towards over time

Relating to the discussion after this, and as mentioned above, composition has been identified by many as a dead end when taken too far for the reasons discussed. What I would suggest you try is a somewhat monolithic approach where you configure an entity that can do everything via feature toggles. These feature components are then internal and designed to make their relationships clear. You would potentially still use components, just that these themselves aren’t as atomic as before either. And wouldn’t be used to ‚program‘ by composition. This assumes you are done with prototyping and want to implement the actual system with well defined rules/features.

earnest gazelle
#

Which one is a good name for a bool field to describe player characters and others (npc, enemy, etc.)
IsPlayerOwned, IsControllable, IsPlayerCharacter, IsPlayerControlled, IsFriendly, IsPlayable, etc.

For example in a strategy game

wraith spear
earnest gazelle
thin aurora
#

The only thing to mention here is that generally methods or properties that start with is indicate a boolean field

#

However, in terms of who "owns" something, why not hook directly on a reference to the owner? For example, your item has a reference to the player when it's owned by the player. This is much more useful.

#

You can pattern match to check if it's owner by the player then, maybe even making a property that does it for you

rocky jackal
#

I have my bounds set up like this so they should have a width and height of 150 but debug loging the bounds.width.x and bounds.width.y gives me this

simple egret
#

You're getting bounds.size.* into your variables, check that it's intended

#

Size is indeed 100 on both axes here

rocky jackal
#

oh its position and size, i thought it was min and max that you define in the inspector

heady iris
heady iris
#

I spent most of Thursday trying to break a large module into many small ones

#

right now it has a bunch of "feature flags", and I thought I could break those features out entirely

#

I realized that it would be...

#

fake composition?

#

the new modules would depend very tightly on each other

rocky jackal
#

Shouldnt this make me a gradient circle that fades to black towards the edge of the texture, cuase it gives me an entirley white texture ?

heady iris
#

fadeFac is zero

#

tex.width is an integer, and you're doing integer division

#

divide tex.width by 2f and it should start behaving

rocky jackal
#

thank you, it works now

heady iris
#

if I hadn't spotted that, I'd have said to log the value of tex.width and fadeFac and see what you're getting

spare dome
#

I'm looping through an array to see if objects are either red or blue, I'm currently stuck on how to see if both red and blue objects are in this array so I thought to use a Boolean as that is all I need to check but only 1 of the 2 Booleans is active at all times (which usually is the object that entered the area first). Any ideas?
Objective.cs
https://hatebin.com/ojqqckdoqh
LocalTeam.cs
https://hatebin.com/vrvrmqfspq
arrays are not my strong suite 😅

heady iris
#

I might just use a hashset, tbh

#

especially if I'm planning for there to be many teams in the future

spare dome
#

I've never used a hashset before, I'll check it out

heady iris
#

For just two enum values it'd be a little silly

#

But I doubt the performance matters whatsoever

knotty sun
spare dome
#

I would have never guessed that and after messing with my code for a bit it does work

stiff wasp
#

Any professional C# dev here open to having a look at my code and giving me feedback?

#

1 script, ~400 lines, gamemode manager.

cold parrot
# heady iris fake composition?

imo you can still break stuff out into components, just not in a way that enables editor-programming. At restore-from-serialized-data time, you will come to hate your components though, if you aren't careful.

heady iris
#

I have that mostly nailed down

#

I don't do "saved games", just serialization of configuration settings on my entities

#

each module gets a GUID when it's attached in the editor, and it uses that to write/read its config data

#

Now I'm thinking about saving the rest of the entity's state too. Great.

short siren
#

Could any of you help with this error?

cold parrot
short siren
cold parrot
#

it also seems to have many sequels.

short siren
#

So what should I do?

heady iris
heady iris
#

step 2: ow ow ow

short siren
#

Ok thanks

heady iris
#

I think I'll tackle that at the same time that I make a multiplayer game

#

Or maybe before.

#

I feel like being able to serialize and deserialize the entire game-state at will is a prerequisite for making a muiltiplayer game

cold parrot
#

which doesn't really give you anything

#

it also leads to overarchitecting a project towards serialization

#

imo serialization and multiplayer are just components of a much larger problem set

heady iris
#

I may be biased because I've been looking at rollback networking

#

where you do genuinely need to go back in time and re-simulate the game over and over

cold parrot
#

yes, but what is that "game" you do need to resimulate

#

its just the runtime state of who has how many HP and in what position, there is so much stuff that isn't part of that

heady iris
#

ah, true

#

What would be an example of something that isn't part of that, though?

#

Beyond something obvious like background clouds

cold parrot
#

effects, player settings, server-only state, achievements, player cosmetics, microtransactions, single-player mode, spectator mode, bot-mode

heady iris
#

oh, well, yeah

cold parrot
#

basically everything that is not "competitive"

heady iris
#

when I say "game state" I'm talking specifically about data that changes over time and affects how the simulation proceeds

cold parrot
#

it would be annoying to have "fully serializable gamestate" and that to force your entire game code to be implemented on the constraints of that

heady iris
#

it would be very silly to add rollback for your settings menu

cold parrot
#

yes

heady iris
#

finally, smash players will be happy

cold parrot
#

but thats what you get when you over-emphasise one aspect

heady iris
#

i mean, that's over-emphasizing it well beyond the point of paroady

cold parrot
#

take another example, message pipes or dependency injection containers... suddenly everyting needs it

heady iris
#

every instance of DI I've ever seen goes one of two ways:

  • In our DI framework, you pass parameters to functions to make them do things
  • 500 layer lasagna that makes no fucking sense
cold parrot
#

'cause, whats the point if its not used everywhere, right?.... right?

heady iris
#
public int Add(int x, int y) => x + y;
#

as far as I can tell, this is DI

cold parrot
#

its fine in theory, very bad in practice. Unless you have some lead developer who does like nothing more than beating people into submission.

#

endless pull request reviews, lots of whining about "bad colleagues" who "just dont get it" or "just dont care".

heady iris
#

every time I open the Zenject readme my brain explodes

cold parrot
#

hehe

#

zenject is a bag of torture tools

#

for some reason they thought its a good idea to allow you to do everything, including all antipatterns, with minimal resistance

heady iris
#

I can kind of see how this could help me in one place

#

Each setting in my game is a scriptable object asset

cold parrot
#

yeah, its great in theory

heady iris
cold parrot
#

but mind, everything turns into runtime errors that are impossible to trace

heady iris
#

I reference this in my "graphics controller" singleton

#

It is slightly weird to have...

public FloatSetting framerateTarget;

and to only have one possible correct assignment for this field

#

I can't reasonably put anything else in there

#

So it feels weird to have the option in the first place

cold parrot
heady iris
#

it's my special highway

cold parrot
#

hehe

heady iris
#

I really like how it works out

cold parrot
#

its fine in personal projects imo, but try making others use it carefully and correctly 😄

heady iris
#

I have a single "Float Entry" prefab that can display any kind of float item (and a Float Setting is, of course, a Float Item)

#

which correctly responds to changes to the item and raises events when it wants to change the value

cold parrot
#

you know thats just scriptable object architecture and basically a global variable 😛

heady iris
#

Right. It's meant to a global, in this case

#

In other cases, I don't store the state inside of the asset itself

#

it's just a key you can use to look up a value from something else

#

each entity's module has some configuration in a ConfigData. You can give it a FloatConfigItem to get or set the current value

#

(hey, that looks really similar)

#

I was thinking of collapsing config and setting items into one thing, but I like being able to do floatSetting.value instead of having to do something like SettingRegistry.GetFloat(floatSetting)

delicate shoal
#

this good? its using C, and GMP for 16MB variables (just in case)

heady iris
#

I have no idea what I'm looking at

delicate shoal
#

it says "Prime #prime-number's-order Number: prime-number"

heady iris
#

Does this have anything to do with Unity?

delicate shoal
#

no but does with scripting

heady iris
#

This is a server for the discussion of the Unity game engine

delicate shoal
#

ik but this is code-general

#

mb

rigid island
#

in a Unity discord..

thin aurora
#

Also, nobody has any idea what you're talking about

delicate shoal
#

yea, a discord of a game engine

delicate shoal
heady iris
rigid island
#

so if its not a Unity topic it belongs elsewhere

delicate shoal
#

its out-of-context

rigid island
heady iris
#

jinx

delicate shoal
# heady iris

also idk why it sent the same picture twice, i SS'd that

#

mb

thin aurora
#

If you'd know it would make no sense then why did you post it? 🤔

heady iris
#

sometimes the clipboard simply says no

#

but yes, you'll want to find a more general programming server

#

I was about to point you to the C# one but this also isn't C#

delicate shoal
rigid island
#

maybe google The Coding Den

night storm
heady iris
#

It is one! I gave it a custom icon.

#

When you assign an icon to a script asset that defines a ScriptableObject, all assets of that type get the icon

#

(but not to derived types -- hence that "Icon Setter" window)

#

it finds all of the children of a type you specify and gives every instance of all of them the icon

night storm
#

oh that's cool, i didn't know that was possible!

fickle trellis
#

Hello, I am having a weird issue that I was hoping someone could help me with. I have 2 GameObjects with the same script that refences a ScriptableObject to move the GO based on a state in the game. The ScriptableObjects are of the same type but are 2 different objects. There is a enum flag variable that they both have that are set to the same value in the inspector - in this case they are both set to "All". However, when evaluating this variable using the same exact code, one is evaluated at the proper "All" and the other is evaluating at "-1". I am losing my mind trying to debug this because the values should be the same
Here is the enum type that the variables are:

[System.Flags]
public enum VectorXYZ { 
    X = 1 << 1,
    Y = 1 << 2, 
    Z = 1 << 3,
    All = X | Y | Z
};

How they are both set in the inspector: https://gyazo.com/1aa611ddc307d7fef73e9d937626491e
The correct evaluation: https://gyazo.com/5c8fa7161b770450a2fb876c5a484125
The incorrect evaluation:
https://gyazo.com/2bbdfff86c08428bf05854172ffd359b

Also, just to note: I am using Odin to make a cusom inspector, but when I take away the "EnumToggleButtons" attribute, I am still getting the same result. Wasn't sure if the value was not getting set properly somehow using the attribute.

heady iris
#

Would you mind sending the actual assets? I want to see the values that Unity has serialized for the field

#

If you don't want to, you can also just pop them open in a text editor and search for the field's name

fickle trellis
thick terrace
#

is it causing a problem? -1 is equivalent to all the flags being set there

heady iris
#

I know there used to be a bug where multi-editing objects with an enum dropdown would cause them all to get reset

heady iris
#

(or Unity; I dunno who's actually computing the new enum value here)

#

See what value you get if you untoggle something

#

I bet you'll get -2, -3, or -5 if you uncheck X, Y, or Z

fickle trellis
# thick terrace is it causing a problem? -1 is equivalent to all the flags being set there

I see when I take away the Odin attribute there is an option for "Everything" like a standard enum flag field. I can also see that the other fields with my enum type are also set to -1 in the .asset file. I guess I'm just confused why this one specific field is not being recognized by this code:

// All
else if (vectorXYZ == VectorXYZ.All)
{
    newVector = modifiedVector * modifier;
}
fickle trellis
# heady iris See what value you get if you untoggle something

I'm not sure if this is default behavior, but I noticed the file doesn't get update unless an object in the scene changes and then is saved. But once that happens, other variations are saved, in this case it was set to 2 when only X was selected.

heady iris
#

try hitting "Save Project" in the File menu

heady iris
fickle trellis
#

It went back to 14 which is the value for the other object that is working. So it looks like now I have a discrepancy with how Unity says "Everything" is selected (probably the right way to do it), and my "All" flag.

heady iris
#

I'm guessing that you wound up with a -1 in there at some point (maybe before you started using Odin?)

#

a -1 will display exactly like that -- every relevant bit is set, so all of the buttons are lit up

#

It doesn't matter that other bits also happen to be set

fickle trellis
#

I used Odin from the beginning, but it is possible something messed up internally. Also, this field might have been renamed at one point and maybe that caused it to be set to -1. I'd have to go back and check my commits.

I think I might just take that All flag out because as of right now it is rarely used. Probably just be best to set the default value as -1 and let the designers deselect the ones they don't need.

I think my main issue in this case was the value not saving so I'll make sure I'm saving the whole project when editing these.

Thanks for your help @heady iris and @thick terrace !!

heady iris
deep stirrup
#

Hello, is there a proper way to load audio clips from asset bundles? When I try GetComponent<AudioSource>().clip = localBundle.LoadAsset<AudioClip>(GetComponent<AudioSource>().clip.name); I always get FMOD::Sound instance for clip "fileName" (FMOD error: File not found.) error message and sound will not play. :\

heady iris
#

why would GetComponent<AudioSource>().clip.name be valid?

#

surely there is no clip stored in there yet

deep stirrup
#

I made my own localization system and I put localized clips into the bundles with exact name as the main ones

heady iris
#

ah, I see

deep stirrup
#

I tried using name of the file directly, and tried use it with extension and full path, but nothing change

heady iris
#

I'd check that the assets actually exist in the bundle

#

You could use LoadAllAssets to check that

deep stirrup
#

okay, I'll try, give me a minute

zinc parrot
#

I know this is just because I dont understand matrices fully yet, but I am also having trouble finding an answer to this online
If I get the cameraToWorldMatrix and perspectiveMatrix from a camera and copy them, how can I change those copies to behave like they were from a camera with a different pixel width/height?
aka, how can I modify the matrices so that they work properly for a different screen size than the camera renders to?

deep stirrup
#

in fact, the channels of the loaded audio are just empty

deep stirrup
#

okay, apparently, this check box fixes the issue

heady iris
#

@oblique lagoon -- I used to have code that depended on the Unsafe class for some nefarious activities (my favorite kind)