#archived-code-general

1 messages · Page 202 of 1

rigid island
#

wdym by this

simple egret
#

Keep your last frame's position and rotation in a variable. That way you can raycast from the last point towards the current point

#

And then if the ray hit anything, you have the hit point

neon plank
#

Any tip about how can I avoid this with my ragdolls?

simple egret
#

Probably nothing with code

leaden ice
#

game devs have been trying to figure that one out for decades

rigid island
neon plank
#

My colliders? In which sense?

rigid island
neon plank
neon plank
heady iris
#

this looke like you need more damping or less aggressive angle limits

rigid island
#

also add some angular vel friction on Rb

neon plank
heady iris
#

Allowing for wider angles, and reducing how much force is used to maintain that, if applicable

#

dunno how your ragdoll is set up

neon plank
#

It was a time ago I did this but I took a T pose object, make unity to create the ragdolls, and then I tried to apply that to my enemy, because applying it directly didn't work :/

rigid island
neon plank
heady iris
#

Is the ragdoll made up of CharacterJoints?

rigid island
#

here this might help (its timestamped to issue)
https://youtu.be/RB18IyKZiB0?t=735

Learn the creation workflow for Ragdolls in Unity, how to toggle between an Animator and Ragdoll, and think through some optimization ideas when you have a large number of potential ragdolls in your game!

Ragdolls are a hugely popular mechanic in games that add, usually a funny mechanic into your game. What they always do though, is allow you t...

▶ Play video
heady iris
#

if so, you can set the twist and spring limit spring and damper values.

#

Non-zero values will make the limits soft.

thick socket
#

should I have to worry about if another object moved out of the path during that time though?

#

aka it might have passed through it last frame

#

but now raycasting this frame will have it hit nothing?

neon plank
#

(I'm making a gif to show the colldiers)

#

In the gif there is a bit of overlapping, but that is because the arm doesn't want to rest

simple egret
thick socket
#

should I still be using raycasts or just colliders if they are "fairly slow" like that?

#

(its not really a bullet but a fireball)

simple egret
#

A non-trigger collider and a rigidbody with continuous collision detection is sufficient

thick socket
#

atm Im using a trigger collider

simple egret
#

Because CCD only works with physical colliders

thick socket
#

oh interesting

simple egret
#

If you do not need the projectile to pass through anything, then regular collider

thick socket
#

a lot of the time I need it to pass through multiple things

#

enemies need their proj to pass through enemies and platforms for ex)

#

player proj just need to pass through platforms

simple egret
#

You can use layer-based collision detection then, make it ignore collisions between two layers via the Physics settings

thick socket
#

gotcha, was worried about how much "knockback" might happen if it wasn't a trigger

simple egret
#

A trick is to set the projectile's mass to the lowest value you can (near zero) and it won't apply any visible knockback

strong cypress
#

Is there really no way to get these values from AnimationClip in code

warm stratus
#

Hey, how to unload a loading scene? I currently have this code

private IEnumerator ChangeSceneAfterLoaded(string sceneName, float minimumLoadingTime)
{
    AsyncOperation sceneLoadingOperation = SceneManager.LoadSceneAsync(sceneName);
    sceneLoadingOperation.allowSceneActivation = false;
    yield return new WaitForSeconds(minimumLoadingTime);
    sceneLoadingOperation.allowSceneActivation = true;
}
rigid island
#

with them

strong cypress
#

insert an animation event at runtime using the frame # (stored in a csv file)

#

But seems like you can only get start/end frames from ModelImporter

rigid island
strong cypress
#

yeah but that is not attached to AnimationClip so can't access that detail in runtime
I will probably use an editor script to just extract the start/end frame and put it in a scriptable object or something

rigid island
#

hmm could get the length in seconds i suppose ? do some math to get the frames (idk how I stink at this)

thick socket
#

not sure why an event would need to be changed at runtime

#

figure in code you could change what the event does

rigid island
#

yeah i dont get the usecase for it as wel

thick socket
#

Tbf Im pretty nub with animation stuff tho

strong cypress
#

yeah i may just do that. it's a weird usecase
previously our attack system used timings instead of animation events
so the attack triggered a specific timing instead of based on a frame #

#

so it would be better for us to just refactor it to properly use animation events

thick socket
#

Ah I had that also

#

Trying to line up cooldowns+animation without animator events sucked

#

You would think a 0.3s animation and waiting for 0.3s would work

#

Only sometimes lol

strong cypress
#

yeah exactly

thick socket
#

I would put in animation events everywhere and refactor

#

Sounds like less time long run

rigid island
#

put like an Action to invoke as the Animation Event , then plug/listen whatever methods u want to it

#

UnityEvent also works if you're working with designers and need inspector to assign methods

strong cypress
#

thanks

hard viper
#

Let's say I want to make a list of classes that are all derived from a generic base class. Is there a simple way to do this?

tulip cosmos
#

oops

rigid island
heady iris
#

MyType<Foo> and MyType<Bar> are completely different types

#

and MyType<object> is not a supertype of MyType<Foo>

#

This is a problem I ran into recently.

hard viper
#

I think I am regretting making my parent class generic, because now I don't have easy access to parent functions

heady iris
#

each of which declares its own state machine type

tulip cosmos
#

Hello, I'm currently using Physics2D.Raycast for my turret to check if target can be seen. To achieve that, I'm iterating over every single enemies on the map (that can be up to 50 or more than a hundred little creatures) and do the following:

  1. Compare distance with the previous nearest enemy
  2. If nearer, Raycast (on the enemy layer only) to confirm it is a visible enemy
  3. Replace previous enemy if it is both nearer than previous enemy and visible
    So this is how my turret works, problem now is I can have multiple turrets, and one is fine, but I tested with 40 turrets and I'm down from 400+ FPS to less than 30.
    Any better implementation for my usecase ?
    (Top down game btw)
heady iris
#

and each of which references an instance of that state machine type

#

I wanted to be able to put common logic in the EntityState class (e.g. a "try set state" method that would ask the state machine to enter the state you called that method on)

#

But that would require knowing the type of the state machine

#

So EntityState would need a type parameter

#

which would make it impossible to refer to any arbitrary EntityState

#

Never had it come up yet.

rigid island
hard viper
#

right now I have:
FixedSpawnpointBase<T> : Monobehaviour, ISpawner
FixedSpawnpointType1 : FixedSpawnpointBase<MyType1>
FixedSpawnpointType2 : FixedSpawnpointBase<MyType2>
DifferentTypeOfSpawner : Monobehaviour, ISpawner

heady iris
#

it feels like a situation where c++ templates would work

hard viper
#

I want to work with functions in FixedSpawnpointBase, on objects exclusively from derived classes

thick socket
tulip cosmos
#

They could be anywhere on the map, depends where the player puts them

heady iris
thick socket
#

but you could even just put like 3-4 colliders on a turret each closer so you only iterate over the closest few and grab the closest one

#

if no target move further out

#

another option if fixed map size, is to have colliders not on turrets, but around the map to essentially "split" the map into sections

#

grab the closest section and iterate over it, if no enemy grab the next one

#

etc

#

imo the colliders on each turret would be easiest to implement

#

(the collider setup is how my enemies currently work, they do different actions depending on which collider player is touching)

hard viper
wicked river
#

Need a little assistance. After trying to create a inventory/Ammo system I started getting this error:

hard viper
#

assume it will get worse in future if I don't figure it out early

heady iris
heady iris
wicked river
#

let me try. Thanks

heady iris
wicked river
#

Nope I think I am causing the error 😭

tulip cosmos
heady iris
#

This error generally appears when you're doing something wrong with the Collections system.

#

(not System.Collections -- the Unity collections package)

thick socket
heady iris
#

TempMemoryLeakValidation

#

Restart the editor. You should get more information about the source of the problem.

hard viper
#

FixedSpawnpointBase has functions that other ISpawners really don't need to implement

#

and that I need

wicked river
thick socket
#

@tulip cosmos ignore the timestamp but this video and the next one show how he uses SO and colliders to do something very similiar to what we were describing

tulip cosmos
#

Oh perfect, thanks !

heady iris
thick socket
hard viper
#

I need to store an object of type T

#

which implement a given interface

heady iris
thick socket
hard viper
heady iris
#

Explain what ISpawner is. It looks like you aren't actually using that interface at all right now.

hard viper
#

ISpawner is an interface so spawnedentityhandlers (components on what is spawned) can report back their status, of if they despawned or died, so spawner knows if it is allowed to respawn

thick socket
heady iris
#

so why not give it a TrySpawn method that tells it to check if it can currently spawn something, and to do so if possible?

#

I don't understand where the hangup is.

hard viper
#

ISpawner does not implement a generic TrySpawn because that really should not be public for some spawners

wicked river
#

Found the issue.
I was using a scriptableObject as the dictionary key and Unity really does not like that

#

Thanks for the help

hard viper
#

idk maybe I could make the interface do more work

heady iris
thick socket
heady iris
heady iris
#

FixedSpawnpointBase<T> would then implement that method.

rigid island
heady iris
hard viper
#

hence why I ask

heady iris
#

casting to a more specific type

hard viper
#

because otherwise this is going to spiral out of control

thick socket
#

not much harder to just make a struct/class to hold all the info I need

heady iris
#

wot

thick socket
#

or sometimes I would just realize I need slightly more info and want to store like 3 things instead of key/value

#

and key/value/value gets confusing 😄

heady iris
#

I frequently make dictionaries mapping keys to small classes

#

to hold several values

rigid island
heady iris
#
    private class EntityInfo
    {
        public float t;
        public bool present;
        public bool entered;
    }

    private Dictionary<Entity, EntityInfo> entities = new();

an excerpt from a component that sends signals when entities enter an area, but only after they spend a long enough time in the area (same for exiting)

wicked river
heady iris
#

If the weirdness persists, do a Reimport All

thick socket
#

¯_(ツ)_/¯

heady iris
#

Assets menu up top -> Reimport All

heady iris
rigid island
heady iris
#

dictionaries with unity objects as keys are super useful.

thick socket
#

for what

heady iris
#

that's like asking what lists are useful for

rigid island
#

lol

thick socket
#

so basically anytime you would use a list...you just use a dict instead?

heady iris
#

no

#

they're two different concepts

rigid island
#

its like one of the most basic form of "database" you can have

wicked river
#

can one event do to much 🤔

heady iris
#

A list is used to store an arbitrary number of things

#

A dictionary is used to relate an arbitrary number of things to other things

rigid island
heady iris
#

lemme find some random examples from my code

thick socket
#

maybe I just dont have many use cases

heady iris
#
private Dictionary<CompletionToken, float> countdowns = new();

CompletionToken is part of my game's AI. They keep track of when an entity has finished a (possibly very long) sequence of actions

#

I use this in a debug component.

#

When a token is marked "done", I do a 1-second countdown before throwing it out

rigid island
heady iris
#

so that it doesn't instantly leave my debug view

#

this dictionary holds those countdown values

wicked river
# rigid island huh?

Well if the scriptableObject in my dictionary is not the issue, then only thing I can think of is the Events.
Upon equipping an item I raise an OnEquipEvent and I have 4 classes waiting for a scriptableObject.
Inventory
UiManager
AmmoManger
EquipmentManager

is it possible the date can't get passed around fast enough?

thick socket
#

I've got a massive playerInventory tho

rigid island
ionic isle
#

just made some good code!!!

lean sail
# thick socket so basically anytime you would use a list...you just use a dict instead?

simple use case: say you want to associate a bunch of items to some ID. Typically GUID's are used which is just some long random string. A dictionary is useful here
You REALLY dont want to associate this with just index [0..n] because if you rearrange the items, you now have major issues where you lost the previous ID and would need some mapping for it, and now dictionary is relevant again

ionic isle
#

its only 20000 lines!

thick socket
scarlet kindle
#

I'm running into a problematic situation where I have a list of SOs that are cards, and i need to remove specific cards selected from the deck... I'm trying to use List.Remove(card) but it removes the first instance it finds of that card when there are more than 2 of the same card in the deck, is there a way I can use the unity GUIDs or something to identify the unique instance of these duplicate and remove a specific one from the List?

thick socket
heady iris
#

They're literally the same thing

#

Perhaps you want to instantiate each card before putting it in the deck, so that each object in the deck is a unique instance

rigid island
wicked river
#

no worries.

heady iris
#

There's no such thing as "not getting passed around fast enough"

heady iris
#

the events aren't happening asynchronously or something

thick socket
#

one of the cases where giving it an id and using a dict might be good

wicked river
thick socket
#

not sure if its what you are doing

scarlet kindle
thick socket
#

but you shouldn't be modifying data in SO during the game

thick socket
#

you could be making a copy of it

wicked river
heady iris
#

I presume you have a folder full of card assets.

#

And that you've put these card assets into the deck list.

#

Is that correct?

scarlet kindle
#

yes, there's a list of SOs that are in the deck list

heady iris
#

and you've dragged the same asset into the list more than once

scarlet kindle
#

yep

lean sail
heady iris
#

If you have 52 cards in your deck, but there are only 26 unique assets and you've dragged each one in twice

latent latch
#

You can give SOs GUIDs but if you use like createinstance youll have duplicate Guids

heady iris
#

then your list only contains 26 unique objects

latent latch
#

unless for some reason you want to create a new guid on instance creation

heady iris
#

the two copies of the card named "Foo" are references to the same object

#

there aren't two "Foo" objects

#

there are two references to the same object

#

It doesn't matter if you slap an ID on the card. The two references in that list will point to the same card with the same ID.

#

What you can do is create a new list and Instantiate each object in the old list, then put the result in the new list.

#

you will now have a list of 52 unique objects.

#

They will be unrelated to the 26 assets. Instantiate creates a copy.

#

the two "Foo" cards in your new list are references to two completely separate objects

#

(neither of which is the object corresponding to the asset)

scarlet kindle
#

ok that makes sense! So

cardStack = new StackList<Card>(); foreach(Card card in startingDeck.cardList) { ** // this was problematic, add Instantiate line here and Push the new object into the stack instead** cardStack.Push(card); }

heady iris
#

Right.

#

You would run into the exact same issue if you were using GameObjects (or any other unity object type, like MonoBehaviour)

#

You'd have multiple references to the same object, which are completely indistinguishable

#

I guess you could write a method that skips the first n-1 instances of an object so that it can remove the nth one

#

but that sounds annoying

scarlet kindle
#

so once I fix that, then the List.Find() should be able to identify the duplicate card types as unique instances?

heady iris
#

Right. Note that these new instances are not related at all to the instances that came from the assets

#

so

#
[SerializeField] Card card;

void Awake() {
  Debug.Log(card == Instantiate(card)); // returns false
}
#

If you still want to be able to check if a card is a specific kind, you might want to do something like this

#
public class CardDefinition : ScriptableObject {
  public string cardName;
  public float coolness;
}

public class Card {
  public CardDefinition cardDefinition;
}
#

So you wouldn't be directly using the scriptable objects.

scarlet kindle
#

yea i've been using a name variable as an identifier anyway

heady iris
#

You'd be creating a Card from a CardDefinition

#

That's what I wound up doing for items in a soulslike game

#

A scriptable object is used to define the weapon's characteristics. A weapon prefab includes a weapon spec

#

So your hand and deck would be made of Cards, which are a container for a CardDefinition and any other runtime data you need

scarlet kindle
#

yea I know that eventually I probably will need to do something like that, if I intend on having modifiers for specific instances of specific card prefabs (like adding a bonus to a specific instance of 1 attack card)

heady iris
#

maybe a list of modifiers applied to the card, if your game allows for that

#

yeah

#

now you've neatly separated the read-only definition of the card from the stuff that can change as the game progresses

#
public class CardDefinition : ScriptableObject {
  public string cardName;
  public float coolness;
  public int manaCost;
}

public class Card {
  public CardDefinition cardDefinition;
  public bool free;
  public int ManaCost => free ? 0 : cardDefinition.manaCost;
}
#

if you want to know if a Card is of a specific kind, you can check if card.cardDefinition == someDefinition

#

also, if you want to be able to see the List<Card> in the inspector...

#

just slap [System.Serializable] before the Card definition

#

it's not a MonoBehaviour because it doesn't really have a reason to be one. I guess you might do that if the cards are physical objects in your game world

#

where the card really does "exist" somewhere

scarlet kindle
#

yea I know that refactor is coming, i should probably do it soon... lol thanks a lot im gonna save this convo for later!!!

heady iris
#

np!

wicked river
# heady iris No.

So with the tem Memmory validation on, This is what I see and it just keeps going

thick socket
#

Lists seem to work well tho

wicked river
heady iris
heady iris
#

instead of having a List<Foo> and a List<Bar>, you'd have a Dictionary<Type, List<Component>>, or something like that

#

note the moderate loss of type safety there

lean sail
wicked river
heady iris
#

What version of Unity are you using?

heady iris
#

my suggestion would only have one pool for each kind of component

wicked river
heady iris
#

that's just the Tech Stream release, not a beta or alpha

#

You could try updating to the latest 2023.1.x release.

#

(although, I ran into a weird slowdown when switching from 2023.1.6 to 2023.1.11...)

wicked river
heady iris
#

Does it stop if you get rid of the debug log statements?

#

The allocations are all full of debug text.

#

(also, it's whataburger time, so i must go)

lean sail
scarlet kindle
# heady iris np!

thanks again! looks like doing Instantiate definitely fixed the bug. for now i'll use this approach, until phase 2 of the project where I add in card upgrades. you the man/woman/child/person!!!

rain minnow
lucid dagger
#

Hey can anyone help me with some code ?

#

dont think its that advanced

slim sphinx
lucid dagger
#

its movement based i have a plane game where the object rotatesalong the z axis

#

however i want to cap the maximum angle it can rotate

#

so they cant do 360s basically

#

ive got how to rotate the plane but idk how to cap it

#

i was able to cap the x axis but i cant figure out the z

#

i can send you the code itd probably be easier to understand that way

#

im bad at explaning xD

rigid island
tawny elkBOT
#
💡 IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

VS Code*
JetBrains Rider
Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

leaden ice
tribal sparrow
#

hey, I have a scene like this, and on my hexagones in the back i have a script that has OnMouseEnter and OnMouseExit functions to highlight the hexagons when i hover over them, everything works great except for the UI part. I want the hexagons to not get highlighted behind the UI elements. So basicaly i want the UI elemnts to block the mouse from triggering the OnMouseEnter function. Can anyone tell me the best way to do this?

leaden ice
#

use the event system which is integrated with the UI

lucid dagger
#

ide configured ?

leaden ice
#

this means IPointerEnterHandler / IPointerExitHandler

#

Or the EventTrigger component
(also make sure your camera has a Physics Raycaster on it)

rigid island
lucid dagger
#

i figured it out in the end btw

#

nothing wrong with visual studio xD

rigid island
lucid dagger
#

the code still works tho only installed unity and vs on home pc today so i havent set it up

rigid island
#

just because it works doesn't mean you shouldn't configure it from here on

#

something you need to do before asking code questions.
(this helps rule out basic/syntax errors solved by IDE suggestion)
see #854851968446365696

thin hollow
#

Is there a way to draw a line between two Vector3 coordinates without using debug.DrawLine?
I need to draw a lot of what's basically projectile streaks, the projectiles themselves are just an array of structs with current position and a velocity.
I tried using a pool of LineRenderer objects, but the lag gets unbearable with just a couple of thousand of them.

spring creek
#

I dunno the best way to handle that at all though. Someone else may know. Just my initial thought

cosmic rain
#

Yeah, if a line renderer is being laggy, you're probably reaching the limits of what you can do with the gameObjects workflow.

Might want to look at the profiler first though. Perhaps it's just something in your code, or there's some other way to optimize it.

thin hollow
latent latch
#

There's a low level GL library if you want to delve into that

cosmic rain
latent latch
cosmic rain
#

Anyways, hard to say anything specific without more info(profiler data, code)

lean sail
#

Yea you cant have a real disconnected line renderer. The only workaround I know is some material with transparent sections or hiding parts of it but that still probably wont be feasible for this

thin hollow
#

Ok, so then how can I make debug.drawline work in final game then?

spring creek
lean sail
latent latch
#

VFX graph is pretty good if you wanna generate thousands of particles/strips if you've got a gpu to spare

thick socket
#
public Dictionary<Bullet, ObjectPool<Bullet>> bulletPools = new();
thin hollow
#

Ideally of course relay in the way of "here's an array of coordinates, draw particle at each one"

thick socket
#

but you basically just want a laser?

#

reading up...maybe not...you could just put particles on an object and move the object between the points you want

thin hollow
thick socket
#

so just...bullet trails?

thin hollow
#

yes

thick socket
#

cause I see a lot of tutorials that seem like what Im guessing you want

thin hollow
#

Like 5 fps with 1200 trails

thick socket
#

2d or 3d

thin hollow
#

3d

thick socket
#

trail renderer might be what you need

#

disclaimer: I only do 2d stuff so have no idea wtf this stuff is 😄

cosmic rain
thick socket
cosmic rain
#

They are not running 100k. They were talking about a couple thousand. Which could still be too much.

thick socket
#

ah, thought he said trails for 1200 objects

cosmic rain
#

But without profiling it's hard to say.

thick socket
#

and multiple lines renderers per trail

lean sail
#

If you have 1000s of the projectile even, thatll cause lag too

thick socket
#

if hes pooling them and doesn't have a ton of colliders/rb I dont think that would be too bad?

cosmic rain
#

It's all speculations untill they provide proper profiler data...😅

lean sail
#

And if you dont, your user probably will on their not as good PC

thick socket
#

lol I've got a 3070 and 5y old cpu and forget thats still a good PC 😄

fluid hill
#

Does anyone know why when I press the game scene in unity, I cant see my prefab? For context, im making a 3d space shooter and when i go to the game i cant see the shooter itself even when the camera is placed on it

thin hollow
#

Yeah, I'm trying to profile RN, and as I expected, if I don't spawn new line renderers - no lag, with no changes in code, the only thing that doesn't fire if I don't spawn them is this bit in foreach loop for each projectile struct:

if (p.line)
                {
                    if (!p.line.gameObject.activeSelf)
                        p.line.gameObject.SetActive(true);
                    p.line.SetPosition(0, p.curPos - (p.velocity * Time.fixedDeltaTime * 4));
                    p.line.SetPosition(1, nextpos);
                    p.line.endColor = clr;
                }
spring creek
thick socket
lean sail
spring creek
#

Oh yeah, forgot the channel. Unity Talk is the right place

thick socket
#

I've got bulletpooling and a particle system pooling

#

might keep those separate but anything I pool thats an "object" I'll keep in bulletpooling 👌

cosmic rain
marble spindle
#

is there any benefit to unity ObjectPool like u can write ur own in 10mins

cosmic rain
#

Also, saving 10 min of time is nice.

marble spindle
#

UnityAction + UnityEvent afaik has benefit of appearing in editor and Vector3 not the same thing. Now that I looked at it aint even sure u save those 10mins u need to learn the thing first kekW

dusk apex
cosmic rain
#

But yeah, you can say the same thing about almost any feature:
Why do you need a CharacterController component if you can implement one yourself in 10 min?

#

Probably a better one too.😬

dusk apex
#

Still waiting for a native non-PlayerPref save utility.

#

It's not required but.. then again, it's 2023.

latent latch
#

I wouldn't be surprised if unity's object pool had some extra secret batching methods which you can only do with the source so your methods would always be worse off ;)

marble spindle
#

That was my idea abt it but reliable reddit sources kekW told me its not the case so wtf

rain minnow
latent latch
#

The real kicker to making a good object pool is making it smart enough to load and unload resources when needed

#

instead of just caching yourself a billion GOs for later use

dusk apex
#

Either way, you're pooling so there's only so much you can improve with your own custom pooler. It's a memory allocation vs garbage collection concern, where you'd just need to make time to properly unload stuff.

rain minnow
# latent latch The real kicker to making a good object pool is making it smart enough to load a...

exactly what i do; it's why i always make my own

i have the option to preload a certain amount instead of the entire capacity. you can add more until you hit capacity. it has the option to expand beyond capacity if needed, and will check to unload resources back to capacity when the current active amount is below a threshold

you can choose to recycle the objects which will always grab the oldest spawned item and re-use it (this method cannot expand, obviously) . . .

latent latch
#

Aye, sounds pretty good

rain minnow
#

you can go further and add delayed despawning to objects, similar to Destroy(gameObject, 3f). it's another collection to track but more functionality . . .

left gale
#

I asked this yesterday in #🤖┃ai-navigation but channel does not seem very active, if anyone happens to know anything ...

#

my own 2 cents on the preceeding topic is... please god don't try to use game objects for "bullet"... unless its like super mario 3 bullets

left gale
cosmic rain
rigid island
#

iirc mozilla has one too

ionic ruin
#

building an entity component system. how should I conceptualize cameras

#

should cameras be entities

#

or components of entities

#

or properties of systems

#

or exist on their own, injected into systems that needed them

#

etc.

main shuttle
ionic ruin
#

sorry should have clarified

#

Unity doesn't technically use a pure ECS right?

#

because components both encapsulate data and behavior

#

unity components act as both systems and components

#

right?

main shuttle
# ionic ruin Unity doesn't technically use a pure ECS right?

Unity has 2 forms now, the MonoBehavior way with components like you say, and the #1064581837055348857 way. As far as I know, DOTS ECS is 'pure' ECS, but you can ask those people, it usually comes down to semantics on what pure ECS means.
Still, this is a Unity server about Unity questions, so its quite weird to ask here about building your own game engine. I would assume your graphics library of choice also has a discord.

obtuse flame
#

So I want to add triggers to the red circle as well as the yellow once, however I want to make sure that the red doesn't get trigged if my object is on the yellow. Is there a nice way to do this or is it just put the yellow trigger slightly infront of the red one?

glad nacelle
#

Hello, I'm using ffmpeg with unity by starting an ffmpeg process as can be seen in this image. It works as expected if I play the game in unity editor but If I take a windows build it isn't working. What should I do?

thin aurora
#

Wrap it in a try-catch and log any exception on the screen

#

Generally having a console system in your game to log messages and/or errors is a good idea since you also want to see those in a build somehow.

#

Otherwise idk, I never used this

glad nacelle
#

ohk,i'll try to put this in try-catch. Although it works perfectly in editor. But I thought maybe the ffmpeg folder not getting included in the build

thin aurora
#

Who knows

cinder raft
#

hi everyone, i have just started working on unity 3d AR foundation , i got the scene set up for AR with the session origin and plane manager and anchor creater and all that stuff, i even got to spawn a character as anchors created but the issue is that i am having difficulty detecting the planes , they take long to detect and feels very glitchy , how can i fix this? and any suggestions on how to start working with AR to make a nice game

swift falcon
#

I have two colliders. I am detecting their collision in the editor by Physics.BoxCastAll() to get their raycast hit.
I want to get the collide point between them.
targetHit.collider returns correct but targetHit.point returns Vector3(0,0,0) always.
The interesting part is, when i give a maxDistance to Physics.BoxCastAll(), it works but that is not what i want since i dont know the direction at first.

The code is:
https://gdl.space/exinazemiw.cs

swift falcon
#

Oh let me add into the pastebin

leaden ice
#

you should also print targetHit.collider.name

swift falcon
leaden ice
swift falcon
#

Oh didnt know that

leaden ice
hard viper
#

If I have a list of X,Y coordinates, and need to find clusters of coordinates in the list which form connected clusters, is the best way to do this a graph-based search algorithm? like DFS/BFS

leaden ice
#

you may need an n^2 first pass where you create an adjacency list using the distances

hard viper
#

Figured. Just wanted to make sure in case there was a lighter/simpler way. ty

leaden ice
#

There may be a fast way that involves spatial data structures like quadtrees

#

it depends on your needs

hard viper
#

i am basically looking through a grid, so it isn’t that shitty to do the search. I need to do a first pass that searches whole tilemap first anyway to find relevant tiles to be consilidated

heady iris
#

Are you trying to find clusters of coordinates that are nearby?

#

or is the idea that every pair of coordinates less than x distance apart are connected?

spark stirrup
#

I have 2 scripts, a terrain generation script, and then a cave generation script. The caves generate below the terrain and now I need another script to cut through the the terrain to create entrances to the caves. I also have a water plane and a cave ceiling that I need to cut through as well. How can I do this?

heady iris
#

The terrain is the built-in Unity terrain, right?

#

So you need to cut terrain holes where the caves intersect the terrain surface.

spark stirrup
#

No I am using a script to generate a mesh using perlin noise

#

I can provide the script if you need

heady iris
#

I'm not familiar with mesh generation in Unity. It sounds like you need to subtract the cave mesh from the terrain mesh, I guess.

spark stirrup
#

What does that mean lol

heady iris
#

Boolean mesh operations combine two meshes. This is a subtraction of one cube from another cube, for example.

#

It'll depend heavily on what your generated meshes look like, and how you generate them.

#

So we do probably need to see those scripts

spark stirrup
thick socket
#

nvm, issue was I wasn't dealing with the colliders offset

spark stirrup
#

Would I be able to create a hole prefab that subtracts it's mesh from all meshes it collides with?

swift falcon
#

what can i use besides playerprefs to save data or can i make in order that playerprefs works when i build the game?

hard viper
#

Playerprefs saves data permanently (even if you uninstall).
We normally save JSON/BSON files for data that persists after application close.

swift falcon
#

i mean there are workin in editor but not when i build the actual game

hard viper
#

are you saving files into the project folder?

swift falcon
#

no

hard viper
#

where are the files

#

are you using application persistent data path?

swift falcon
#

i don t think so

hard viper
#

that’s your problem

#

that’s where you need to send files

swift falcon
#

thanks i guess i will try it

civic folio
#

What's the difference between interfaces and abstract classes?

cunning trout
#

mainly, interfaces can only be extended and abstract classes can be instanciated, just like normal ones

heady iris
#

you can't construct an abstract class

#

An abstract class is like a class, but it can have abstract members with no implementation

#

Deriving classes must override those members.

cunning trout
#

wait sorry I got confused

#

forget what I said xd, listen to Fen

heady iris
#

Interfaces are just a collection of properties and methods. They do not contain implementations of the methods (yes, I know about default implementations; ignore those for now)

#

You can only derive from one parent class. You can implement many interfaces.

#

An interface represents a contract. You promise you can do XYZ.

cyan bronze
#

How to create different development modes inside editor?
For example I want:
Development mode
Game-designer mode

each mode changes the way how to work in editor. Scripts will compile based on this mode. Is it possible only using defines or there is some built in solution?

hard viper
# civic folio What's the difference between interfaces and abstract classes?

Abstract classes need to be inheritted from. C# only allows single inheritance, so you’d be using up your ONE parent. Interfaces do not.

Abstract classes can have implemented methods (methods that actually do things), virtual methods, fields, static fields… the works. Interfaces don’t (but do allow some of this stuff in C#9, which Unity doesn’t allow).

#

@civic folio Example of an abstract class: FixedSpawnpointHandlerBase is an abstract class full of concrete methods that handle spawning (taking in info, requests to spawn, requests to despawn, checking if already spawned, etc).

It is abstract because it has an abstract method to actually spawn something. Child classes are responsible for handling the actual spawning, because different types of objects might have different requirements.

civic folio
hard viper
#

All the children inherit the methods defined in the abstract class.

#

If I used an interface, I would need to copy paste like 10 different functions, and 10 different fields etc to make everything match.

#

Example of an Interface: ISpawner is an interface for any spawner. It has just a few methods for entities to report if they died to the spawner. The spawner could be a fixed spawnpoint, but also could be something totally different (like an enemy that spits out enemies). Either way, the spawned thing needs a way to tell what spawned it that it is dead/despawned. ISpawner has 2 methods for that.

Because it is an interface, the enemy does not care if the spawner was a fixed spawnpoint or enemy or whatever.

#

But everything in an interface is abstract. (for the most part)

heady iris
#

they also cannot define any inheritable behavior

hard viper
#

Every ISpawner NEEDS to define a completely custom method for each requirement of the interface.

#

If you want a bunch of classes to inherit the exact same function, that it inheritance, not interface.

#

And for referenced, my abstract FixedSpawnpointHandlerBase ALSO implements ISpawner

#

the two can be used together

civic folio
heady iris
#

well, they're classes

hard viper
#

abstract classes can define fields

heady iris
#

you can define fields in a class

#

abstract does very little

civic folio
#

never mind

heady iris
#

it just allows you to have abstract members

#

and prevents instantiation of the class

#

that's about it

hard viper
#

abstract class just means you can’t make an instance of the class

#

you NEED to inherit to really use it

#

do you understand?

civic folio
#

yes

hard viper
#

as a rule of thumb, most interfaces have an extremely tiny set of methods. Because anything that implements it is forced to implement each of them

#

abstract classes can get fucking massive, because you are making methods to get inheritted.

#

My ISpawner interface is basically 4 lines long

#

my abstract FixedSpawnPointHandlerBase is about 200 lines long

#

because it actually has its functions and machinery filled out

#

Interface just means “I expect this class to have functions X, Y, and Z, with those return types and arguments.”

heady iris
#

an interface should be a set of methods that accomplish a specific task.

hard viper
#

and they should be super generic

heady iris
#

if Foo implements Damageable, Foo promises it can be damaged.

hard viper
#

ISpawner’s methods are:
-Get prefab the spawner makes
-Request spawner to spawn something
-Tell spawner that something it spawned died
-Tell spawner that something it spawned despawned without dying

#

any spawner should realistically be able to do those 4 things, no matter what shape or form it takes

#

It also doesn’t explicitly ask for the spawner to do something too specific.

#

Like with Fen’s IDamageable, you would want something like “RequestTakeDamage”, more than “ForceTakeDamage”. This way it is clear that the thing implementing the interface is deciding wtf to do when information is passed into it.

#

That’s all I got for now. Make sense?

#

RequestTakeDamage is smarter because we might want some things to implement invincibility or invincibikity frames later. And we don’t want to micromanage that shit. That is the responsibility of the IDamageable to decide what to do with the incoming damage request.

#

One last note; Interfaces CAN enforce properties. So you can’t make a field, but you can force anything that implements it to give a getter for something.

split patio
#

do you know any toturial for making a game like "Dark Messiah Of Might And Magic " in unity or skyrim (just sword fight ) ?
i need these 3 things
1- first person melee combat just like Might And Magic (sword fight , defend and kick and the part 2 sowrd stuck and you have to press left button fast )
2- npc ai behaver ( i loved the part when enemy health was low they were ran away ) , walking
3-i need learn to make stronghold crusader ( the part i order units to move or make a place for workers and workers work like wood cutters )

I would appreciate any help you can give

#

also do ai in unity is a real thing ? like can i actually ask for code from it ?

#

( i want tutorials not the ai code thing was just a question )

rigid island
#

thats a good ass game

#

made in source

warm stratus
#

Hey, How to unload these scenes?

raw glade
#

is there any way to enable read/write of texture through script?

knotty sun
late lion
# raw glade is there any way to enable read/write of texture through script?

Only if you're creating the texture. If a texture has already been created and loaded, then you can't change read/write after the fact. Read/write determines if Unity will unload the texture data from the CPU after it has uploaded it to the GPU. Once it's unloaded, it's unloaded and you can't get it back without reloading the whole asset from disk again, which you can't do from script.

raw glade
#

okay thank you

raw glade
knotty sun
raw glade
knotty sun
#

no, that is a Read operation not Read/Write

#

you can also use GetPixelData/SetPixelData

heady iris
#

read/write enabled must be checked either way. it keeps a copy of the texture in main memory.

#

isReadable is set to true if "read/write enabled" is checked

#

I presume you can blit the texture into a new texture that is marked as readable, though.

heady iris
#

mildly surprised you can't just ask to have the data copied back from the gpu

knotty sun
#

you can

raw glade
knotty sun
#

you only need Read/Write if you use GetRawTextureData. GetPixelData should work fine

heady iris
#

This method returns a NativeArray<T0> that points directly to the texture's data on the CPU and has the size of the mipmap level. The array doesn't contain a copy of the data, so GetPixelData doesn't allocate any memory.

#

if the data isn't stored in main memory, then this would not work

heady iris
knotty sun
heady iris
#

just checked. throws an exception

#

UnityException: Texture 'Icon' is not readable, the texture memory can not be accessed from scripts. You can make the texture readable in the Texture Import Settings.

knotty sun
#

not documented then

heady iris
#

the data does not exist anywhere in main memory, so it is impossible to read it.

#

it would be useful if it explicitly mentioned isReadable, yes.

knotty sun
#

sure there is a graphics api you can use but then the texture needs to be in GPU

heady iris
#

it looks like this only copies data on the cpu side if both textures are readable

knotty sun
#

yep, needs GPU textures to bypass this

heady iris
#

you can use Texture2D.ReadPixels to copy from the current render target to any texture, which will let you pull data out of the gpu

sage latch
#

I'm loading a scene and trying to run some initialization logic right after, but it happens in a weird order:

Debug.Log($"Loading scene");

var operation = SceneManager.LoadSceneAsync(sceneIndex, LoadSceneMode.Single);
yield return new WaitUntil(() => operation.isDone);
        
Debug.Log($"Loaded scene");
```And I get this order of events: 
- Loading scene
- Start is called
- Loaded scene

Also tried callback but no difference```cs
Debug.Log($"Loading scene");

var isDone = false;
SceneManager.sceneLoaded += SceneLoaded;
SceneManager.LoadSceneAsync(sceneIndex, LoadSceneMode.Single);
yield return new WaitUntil(() => isDone);
        
Debug.Log($"Loaded scene");

void SceneLoaded(Scene scene, LoadSceneMode mode) {
  SceneManager.sceneLoaded -= SceneLoaded;
  isDone = true;
}
heady iris
#

You're probably getting punked by the timing of the coroutine.

#

WaitUntil will check the condition after Update and before LateUpdate

#

So it will only allow the coroutine to proceed after Update is completely over (which means it'll be after Start runs in the new scene).

I do not know exactly when the scene actually gets loaded.

sage latch
#

ill try async await

heady iris
#

what if you just log inside of that SceneLoaded method?

#

see when it fires

sage latch
#

it is before

rocky jackal
#

will OnCollisionEnter() also be called if a child object wich has a collider hits another collider ?

rigid island
scarlet kindle
#

I have a scroll rect canvas that contains some inner objects, it appears that the rect raycast target is in front of the children objects sitting in the masked canvas of it... is there any way to have IPointer events from the children trigger in this setup?

floral coral
#

Is there a way for me to have a const/static/other way to make a variable global gameobject, that is in the scene? I have the main camera on an "arm" that is on a "swivel" to make a third person camera, and I want to be able to access the camera's "arm" and "swivel" like I would the camera with Camera.main

heady iris
#

you'll want to use static somewhere, yes

heady iris
scarlet kindle
#

if i move the removalcardUI object out of the deckviewer (and disabled it), the Ipointer events work on the card

#

i guess I could go with the old input system like OnClick? i'd rather not have to do that though

#

moved to UI

heady iris
#

ah, that'll do it

wary grail
#

hey guys, I've got a very simple editor build script that builds for Windows, Linux and Mac with a single click, but Im running into a problem where for Linux, Im getting "cannot find clang.exe". The caveat is... if I manually switch the build target to Linux and build (either using my own script or the build button from unity) it works as expected... anyone has run into this issue before? (using Unity 2020.3.25)

heady iris
#

SuperUnityBuild is perfect for this kind of thing, btw

#

but if you want to track down the bug in your own script, are you sure you're correctly changing build targets in your script?

wary grail
#

Im basically just calling "BuildPipeline.BuildPlayer(options);" where the options set the target to be StandaloneLinux64, its as basic as it can be. I dont switch the editor platform because that interrupts my own script from running lol since the editor reloads

grim mantle
#

hi can some1 help me pls? i have problem with paint texture when i use it unity gets super slow.

heady iris
#

you will have to provide some details...

heady iris
#

I don't know much about build scripting unfortunately

#

Perhaps Unity is setting a $PATH variable depending on which editor platform you're set to?

#

dunno.

acoustic sinew
#

Currently having an issue where my vertical mouse movement is not rotating the camera up or down. The horizontal motion is working, just not the vertical.

float mouseY = Input.GetAxisRaw("Mouse Y");

if (Mathf.Abs(mouseX) > 0.0f || Mathf.Abs(mouseY) > 0.0f)
{
    Vector3 rotation = new Vector3(0.0f, mouseX * rotationSpeed, 0.0f);
    transform.Rotate(rotation);

    
    Camera mainCamera = Camera.main;
    Vector3 cameraRotation = new Vector3(-mouseY * rotationSpeed, 0.0f, 0.0f);
    mainCamera.transform.Rotate(cameraRotation);

    
    Vector3 currentCameraRotation = mainCamera.transform.eulerAngles;
    currentCameraRotation.x = Mathf.Clamp(currentCameraRotation.x, 0.0f, 80.0f);
    mainCamera.transform.eulerAngles = currentCameraRotation;
}
else
{
    rb = GetComponent<Rigidbody>();
    rb.freezeRotation = true;
}```
heady iris
#

you're setting the main camera's euler angles

#

hmm

#

I wonder if the euler anlges are actually winding up ranging from -180 to 0 or something

#

you should log them to see what you're getting

#

Modifying euler angles like that can cause surprising results.

acoustic sinew
#

Wait, could it be that I have the rigidbody's rotation frozen in that direction?

heady iris
#

you never unfreeze it

#

so perhaps

#

the rigidbody will already be unhappy that you're setting the transform's position and rotation directly, mind you

#

well, just the position

acoustic sinew
#

That didn't make a difference unfreezing the rigidbody

heady iris
#

Log the value of currentCameraRotation.x before you clamp it

#

Rotating on one axis can mess with the euler angles on all three axes

#

I always store the desired pitch and yaw, and then construct a rotation from those values

acoustic sinew
#

Nothing is getting logged. Just getting "NullReferenceException: Object reference not set to an instance of an object
PlayerController.Update () (at Assets/Scripts/PlayerController.cs:50)" in the console lol

heady iris
#

well, then figure that out..

acoustic sinew
#

It's referencing mainCamera.transform.Rotate(cameraRotation);

heady iris
#

then mainCamera is null

acoustic sinew
#

Ohhhh, wait I just realized I'm an idiot lol. I haven't assigned anything as the "maincamera" and the only reason I'm seeing the camera move is because the camera is a child object of the "player" object 😅

heady iris
#

that'll do it :p

#

Also, you probably want to make that the local euler angles

#

not the world-space euler angles

#

since you're tilting the camera up and down

acoustic sinew
#

Now I'm getting some funky stuff happen lol I think it's due to the camera being a child object of the player. I'm gonna play around with that and come back for some more help later. Thanks

heady iris
#

That much is fine.

#

A pretty common strategy is to parent the camera to the player

#

then rotate the player around the local Y axis and the camera around the local X axis

#

I'm guessing your problem is that you're using transform.Rotate to rotate the camera

#

well, more specifically

#

not using Space.Self

#

transform.Rotate(cameraRotation, Space.Self);

#

you want to rotate the camera around its local X axis

#

X is right

#

so that will tilt it up and down

#

If you rotate it around the world X axis, it'll rotate in all kinds of directions

#

in fact, in this situation, you could just directly edit the localEulerAngles of the camera

#

mainCamera.transform.localEulerAngles += rotationDelta;

hard viper
#

is there a way to make physics2D sync transforms fpr one gameobject/collider? I want to call collider.bounds during initialization, but the position is totally wrong because it hasn't been synced yet to its transform

zinc parrot
#

hey so is there ANY way for me to have an ETC render texture? I plan to write to it through a compute shader that does the ETC compression so its fast, but I need it as a render texture as I cant afford to have the memory cost of having both the render texture and a texture2d hangin out(plus the texture2d will take up space on both the CPU and GPU, doubling how much memory it actually takes)

#

I already have the rendertexture and texture2d at rgba32, but since they are 16kx16k textures, thats still 2 gigs for just the entire texture2d...

#

they are so large as they are atlas's I create on the fly during play since unity doesnt have any way to send an unknown amount of textures to a compute shader at once

devout solstice
#

Ive got a couple classes in a namespace, and im trying to reference one of the classes thats not the main class, how can i do that

latent latch
#

how to call something from another namespace? Just include it at the top of your script.

heady iris
#

not sure what you mean by "main class" here

devout solstice
#

the class that matches the name of the file

heady iris
#

that's only relevant if you want to be able to use the class as a component

#

Unity will look for a class whose name matches the file

devout solstice
#

well i need to be able to use it as a component

heady iris
#

then you need to make a separate file

devout solstice
#

i think

heady iris
#

this has nothing to do with namespaces, btw

latent latch
#

Don't stick monos in the same class

devout solstice
#

i dont

latent latch
#

no support for that with the editor unfortunately

devout solstice
#

i have multiple classes idk what its called but i have it like class : mainclass so the only mono is the main class

latent latch
#

would be nice cause I have like 100+ scriptable objects in such small scripts :(

heady iris
#

put them in separate files

devout solstice
#

man i was trying to avoid doing that

heady iris
#

well, you can't

hard viper
#

more files is better than more problems

devout solstice
#

ill just put them back into the same class

hard viper
#

single giant files generally cause more problems than they solve

devout solstice
#

least i dont have to put 50 scripts on a object or wtv

hard viper
#

anyway, I’m trying to troubleshoot issues with querying Collider2D ‘s bounds. The two main problems are: size is zero if disabled, and it can be desynced from the transform.

#

is there a way to accurately and reliably calculate the bounds of a collider?

latent latch
#

I don't really understand why unity complains about scriptable objects being in a single class. You're using the asset menu attribute to define what SO you're creating an instance of anyway.

#

and usually you want your data files to be somewhat together

topaz plaza
#

Using Hinge Joints it happens that I can only trigger the door opening once. After it's finished moving I can't interact with it anymore. Any idea why that is? I can't find an option that gives me a way to interact multiple times with a door

lean sail
topaz plaza
lean sail
topaz plaza
#

also now removing the limits I try to go around it and push it back and forth. At some point it goes harder and harder and then stops to move completly

topaz plaza
#

oh man nevermind

lean sail
topaz plaza
#

the stupid rigidbody I have attached is actually physically moving away each time I use a door

#

I need to make it kinematic

#

sorry

lean sail
#

No need to be sorry, joints are quite weird to work with

wicked cedar
#

Hi, anyone know anything about how Steammanager works? whenever I build my game and load a scene that has the SteamManager prefab in it with the SteamManager Script, the game just crashes.

rain minnow
hard viper
#

in start

rain minnow
#

just for that one frame?

rain minnow
heady iris
#

does calling Physics2D.SyncTransforms do anything?

rain minnow
#

or you could sync the transforms. ah, beat me to it . . .

hard viper
#

Calling SyncTransforms works. But it affects EVERYTHING in the scene. And there isn’t a more localized option.

rain minnow
#

ouch . . .

hard viper
#

it wouldn’t be such a problem if I could just request a sync of a single transform as I need it.

rain minnow
#

I'm surprised they don't have that option . . .

latent latch
#
public abstract class EntityModification<SO> : Storable<SO>, IEntityModification where SO : EntityModificationSO {}
public class AbilityStatMod : EntityModification<AbilityStatModSO> {}

public class AbilityStatModSO : EntityModificationSO
{
    public override IEntityModification Construct(IEntity entity)
    {
        return new AbilityStatMod(this, entity);
    }
}

public class ArmorItem
{
     public bool EquipItem()
     {
        foreach (EntityModificationSO mod in Modifications)
        {
            //Can't do this because it's abstract
            //var newMod = (IEntityModification)new EntityModification<EntityModificationSO>(mod); <----

            var newMod = mod.Construct(IEntity entity); //Works fine
            newMod.AddModification();
        }
        
        .....
    }
}

Does this implementation seem off? I'm not too sure how to solve this otherwise.

#

Instead of invoking new, I construct it from within the SO because I override a method and return an interface

#

No clue how I got myself into this position

latent latch
#

Yeah, that's probably it unless I make the base class non-abstract, but instances of the base would make no sense. Unless there's a way to do some shennanigans with gettype, but I doubt that works since that's all runtime stuff.

tall gyro
#

is there a way to make retrace lines show in the screen in unity 2d?

heady iris
#

rarytraces, you mean?

#

I want to move like Vector3.Slerp, but with a fixed distance, not a lerp percentage. Any ideas on how I'd do that?

#

If I could calculate the length of the slerp, I could easily calculate a t value.

#

I guess I could just sample a few hundred points and call it a day.

#

you know. i might also just make it so that I tell it how long the move should take, rather than actually setitng a speed

#

that avoids the problem entirely

solid laurel
#

need help with a boomerang im creating. It goes out like fine, but doesn't go back to the player. Any way I can do this?

{
    [SerializeField] private GameObject particleOnHitPrefabVFX;
    [SerializeField] private float projectileRange = 10f;
    [SerializeField] private float returnTime = 0.5f;

    private float moveSpeed = 22f;
    private Vector3 startPosition;
    private float state = 1; //if state is 1, then it is away from player, if the state is 2, then it is coming back to player
    private Vector2 currentPosition;

    private void Start()
    {
        startPosition = transform.position;
        StartCoroutine(BoomerangStateRoutine());
    }

    private void Update()
    {
        MoveProjectile();
        StartCoroutine(BoomerangStateRoutine());
        DetectSwitchState();
    }

    private void DetectSwitchState()
    {
        if (Vector3.Distance(transform.position, startPosition) > projectileRange)
        {
            state = 2;
        }
    }

    private void MoveProjectile()
    {
        transform.Translate(Vector3.right * Time.deltaTime * moveSpeed);
        currentPosition = transform.position;
    }

    private IEnumerator BoomerangStateRoutine()
    {
        //if state is 1, do nothing
        //but if state is 2, lerp back to start position and destroy the gameobject
        if (state == 1)
        {
            yield return null;
        } else if (state == 2)
        {
            transform.position = Vector2.Lerp(currentPosition, startPosition, returnTime); //go back to original spot
            Destroy(gameObject);
        }
    }
}```
latent latch
#

Time to debug

#

Have you made sure that it's changing states and that you're changing the direction that it travels after.

solid laurel
#

I know its changing states but im not sure how to change the direction back

latent latch
#
        transform.Translate(Vector3.right * Time.deltaTime * moveSpeed);```
So you're constantly translating, even when you go into state 2, which is fine, but you also lerp in your state2 there to go back to your postion
scarlet kindle
#

don't you need a for loop?? in your StateRoutine

#

for the lerp

solid laurel
scarlet kindle
#

i dont think translate works the same way as setting the position. it synchronizes the whole motion

just setting position is a single frame command. if you want to move with the position you need a for loop for the lerp

solid laurel
#

ok

latent latch
#

oh yeah where are you updating the lerp time or am I blind

#

either way ya probably one to stick with one method

scarlet kindle
#

yea you could try translating instead if you dont want to lerp it

#

i think one liner without for loop would work in that situation

solid laurel
#

ok thanks

scarlet kindle
#

I have a case statement inside a for loop (not in code sample) and I'm trying to WaitUntil another MB returns true... however, I never get the response from the other MB inside the loop, and the loop just exits. I'm stumped as to how this can happen?

case "SCRY": scryUISelector.isComplete = false; handManager.Scry(Int32.Parse(item.Value)); yield return new WaitUntil(() => scryUISelector.isComplete); Debug.Log("ending scry"); break;

#

the Debug line never prints in the console. I watch the isComplete turn to true

latent latch
# solid laurel ok thanks

I suggest just forgetting the coroutine right now and just move the boomerange to the location you want, switch the state, then do the same backwards.

#

coroutines good for if say you're tossing 20 boomerangs and stuff like that

cosmic rain
scarlet kindle
#

I am absolutely braindead, thanks

#

I didnt make the other MB's method a coroutine

#

oh wait

#

i dont have to do that

#

huh

#

So yea, the method calling the for loop & switch is an IEnumerator. The method from the ScryUISelector is not IEnumerator

leaden ice
scarlet kindle
#

yeah it is

#

debugger line goes up to the Scry method, then i go into the other and watch isComplete = true

#

it isnt stuck in an infinite loop either

#

idk if my debugger is just being weird

#

but, the for loop definitely terminates early, there are more actions left for it to process that it doesn't do

#

and if I remove the WaitUntil line, those actions do process (just out of order)

#

ok i think it's what dlich originally said, i didnt realize the caller of the Coroutine may be disabled by this point in time

vagrant blade
#

You can get the height and width of the screen

flat abyss
#

Alright guys? I'm using multiple colliders like this to detect things like the player and objects, etc. Is it possible to also detect which are overlapping with those colliders and return a list or something?

#

Which tiles* are [...]

lean sail
slow veldt
#

Hey guys so im working on a player movement script for and im wondering if its a better practice to manipulate Rigidbody.velocity directly or to stick to Rigidbody.AddForce() .

#

I feel like using AddForce() is a better decision for the long haul but its gonna be a lot more work for making the controls feel snappy

slow veldt
#

yeah that's true, i think im gonna primarily try to use forces though. that way i can have the player be affected by explosions or other physics objects. I'm having to get pretty creative with it though lol. like for stopping the player instead of using rb.velocity = Vector3.zero I ended up having to use rb.AddForce(-rb.velocity, ForceMode.Impulse);

fervent furnace
#

it should be -rb.velocity*mass? impulse uses mass

slow veldt
next salmon
#

Do state machines and ai behavior trees function the same way? Are behavior trees just a node version of a state machine?

shadow laurel
#

Hey, so I've been having trouble trying to fix this error (InvalidCastException) that keeps occurring (Shown in the screenshots) and I have narrowed down the location to the coroutine "ProcessDeathEvent" however, this should not be the case as the same coroutine works on a seperate game object with similar components. Linked below are the areas of code surrounding the bug

Process death Event Code:
https://hatebin.com/hsyzqnnagn
https://hatebin.com/qfwqaalpau

Check HP (Coroutine running) Code
https://hatebin.com/obygppcdjb

Could I get some help with this please?

cosmic rain
leaden ice
#

Agreed, nothing in that stack trace seems related to the provided code. It seems to be an issue in some netcode editor scripts

void birch
#

Can someone tell me if this is wrong and has an error or right (this is a player wasd movement script

jovial spear
#

Hi, I would like to use Debug.drawray to debug a specific frame of my ingame logic. I use Debug.break to pause the editor at specific frame, but I see multiple rays... how to clear the old rays?

acoustic sinew
#

Currently trying to implement a jumping function into my game. I'm using a raycast to check if the player is grounded, and if so then when the player hits the spacebar it jumps.

Debug.Log(isGrounded);

       
if (isGrounded && Input.GetButtonDown("Jump"))
{
    
    rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
    Debug.Log("Jump");
}``` The raycast shows true, however the if statement condition aren't getting satisfied. I have "Space" configured as the positive setting in input for "Jump"

The Debug check for "isGrounded" does show "True" at the time I am pressing space.
jovial spear
slow veldt
#

no he has it right

#

ur thinking of Input.GetKey()

acoustic sinew
#

I've tried passing a Keycode for "space" but that just throws an error saying "Space isn't configured"

jovial spear
#

oh. sry. i stopped using the old input system 3 years ago

slow veldt
#

do Input.GetKey(KeyCode.Space)

#

although, assuming your input settings are correct, or even the default ones, idk why Input.GetButtonDown("Jump") wouldn't work for you so it might be something else

acoustic sinew
#

It might have been working, I just wasn't seeing "Jump" being printed cause "True" was getting printed so rapidly. However, I did see "Jump" for sure when using your recommendation. My player still didn't jump though, but that could just be changing force variables

slow veldt
#

in that case ur probably better off with the initial code haha. unity's input manager is pretty convenient.

river swift
#

Hey guys... Is there a way to import the binaries to unity without sending with it the source code?

My problem is a designer that insists on messing with the code.

acoustic sinew
knotty sun
slow veldt
#

oh i meant to reply to killer3p0 (im losing my mind)

river swift
#

Not sure it is doable right now, but might consider for the future.

#

The whole "it just added a serialized variable" is pissing me off so much

short shadow
#

Currently well in over my head trying to understand projection matrices (in general but specifically in regard to cinemachine virtual cameras). I'm trying to get the frustum of a virtual camera, so I can check if a world point is within the frustum. My approach so far has been to try and get the 4x4 projection matrix of the lens and combine it with the local transform matrix to get the frustum.

In my head that makes sense but I have a feeling this is completely wrong.

Here's code of the class and the grid system it uses: https://gdl.space/papavaqeka.cs
Ignore the disgusting length of the function, I start messing with getting the matrix at line 112 of CameraManager.cs

Matrix4x4 vcamFrustumMatrix = GetVirtualCameraProjectionMatrix(vcam);
// Combine with camera game object's transformation matrix
vcamFrustumMatrix *= virtualCamera.transform.localToWorldMatrix;```

Have tried researching thoroughly, any help on how to approach please! Also if this should be in beginner please let me know
spark stirrup
#

How can I do mesh subtraction during runtime?

heady iris
#

you're still working on cutting holes for caves in your terrain, right?

spark stirrup
#

Yep

heady iris
#

yeah, I haven't got a good idea of how to pull that off in unity in particular

spark stirrup
#

I found ways to do it using the editor, but not during runtime which is important bc of my procedural generation

heady iris
#

This is a mesh-based terrain

#

one mesh for overworld terrain, one mesh for a cave system

#

that's my understanding

rigid island
#

ohhh mb then

heady iris
#

It sounds to me like you just need to subtract the cave mesh from the terrain mesh, but I have no idea how you'd accomplish that in Unity

spark stirrup
heady iris
#

oh, do you need to carve a path into the cave mesh?

spark stirrup
#

I would plan on randomly spawning a hole prefab that has a script to cut through meshes

heady iris
#

In that case it'd be a similar premise, but cutting both meshes

spark stirrup
heady iris
#

i'm imagining doing this

spark stirrup
#

But I need it to happen inside of unity during runtime

mellow root
#

I am getting CS1001: Identifier expected in "KeyCode" part of the code. How do I fix it?

#
            {
                index++;
        }```
heady iris
#

That is not valid syntax.

mellow root
#

but it is valid

heady iris
#

I can assure you that it is not.

#

. is the member access operator.

#

It may only be used with a literal name

#

Foo.Bar.Baz is valid

#

If you want to store a list of cheat code keycodes, why not just make an array of KeyCodes?

#

Then you could do Input.GetKeyDown(cheatCode[index])

mellow root
#

I did try that but it led to like 10 errors

heady iris
#

well, then perhaps ask about those errors

swift falcon
#

sup nerds

rigid island
#

gottem

heady iris
swift falcon
#

i don't know how to read

#

very rude to assume

rigid island
#

do you also want to get muted?

swift falcon
#

i'm not mute

#

ong stop being rude

mellow root
# heady iris well, then perhaps ask about those errors

"error CS1922: Cannot initialize type 'char' with a collection initializer because it does not implement 'System.Collections.IEnumerable''
"warning CS0219: The variable 'index' is assigned but its value is never used"
"The name 'cheatCode' does not exist in the current context"

rigid island
tawny elkBOT
#
Posting code

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

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

heady iris
#

You've got a number of separate problems here.

swift falcon
#

spamming, i don't see it

heady iris
#

This code does not include an array of KeyCode.

neat forge
heady iris
#

also, I should point out that this just declares cheatCode in Start

fervent furnace
#

you initialize it in local scope

swift falcon
fervent furnace
#

it should be class field

heady iris
#

Local variables die when the method exits.

#

more specifically, they die when their scope ends

#

in this case, that happens to be when the method exits

#

So, yes, move that array out to the class

#

and use KeyCode!

#

KeyCode[] cheatCode = new KeyCode[] { KeyCode.C, KeyCode.H, KeyCode.E, KeyCode.A, KeyCode.T };

#

that oughta do it

#

now you can just check if Input.GetKeyDown(cheatCode[index])

heady iris
mellow root
#

Alright, it works now but I'm getting an error after I have entered it "IndexOutOfRangeException: Index was outside the bounds of the array."

runic granite
#

hi is there anyway to make many game object form shapes? for example i want to make many cube form a heart shape, i mean sure i can do it manually but is there any other good alternative instead of doing it manually?

rigid island
#

remember arrays start at 0 index

#

so 5 elements is #4

#

etc

heady iris
#

I'm guessing this happens after you push all five cheat keys

thick terrace
heady iris
#

You will want to check if you've hit them all and stop trying to index the array

heady iris
rigid island
heady iris
#

press c -> press h -> press e -> press a -> press t

#

-> IndexOutOfRangeException

#

boing

rigid island
#

ahh

mellow root
#

Yes, but when I press d (which is not part of the array) after I entered it, it gets treated as a key from the array. I have else to set index to 0 for that reason but it does not work after I entered the code.

leaden ice
heady iris
#

ah, so you want to reset if you push the wrong key

heady iris
#

Sounds reasonable enough. Show your new code.

rigid island
#

yea i suppose if its a cheat sequence thingy

mellow root
heady iris
#

share your new code anyway.

#

I want to see what you have right now, not guess

mellow root
#

actually shit this one does not work cause I tried to fix it

fervent furnace
#

if !getkeydown will reset the index

heady iris
#

this would instantly reset index to 0 if you didn't happen to push the current index's key that frame

#

that sounds wrong

#

perhaps you wanted GetKey?

#

so that you have to press and hold the keys

#

C
CH
CHE
CHEA
CHEAT

mellow root
heady iris
#

your keyboard might also not handle that many keys

#

If you want to reset progress if you push any other key, then you'd have to check for quite a few different keys

mellow root
#

that is also a posibility

heady iris
#

I don't think there's a convenient way to do that with the old input manager other than checking each keycode in sequence

#

I would just make it so that you have one second to push the next key

#

if you run out of time, it resets

mellow root
#

Idk maybe I'll convert it to the new input system, but this is what my teacher uses

#

So I got used to it by now

#

I got a big brain moment and it works, I just set the index to 0 after the cheat has been activated

#

thank you all

runic granite
heady iris
#

you need to calculate points on the edge of the shape.

#

How are you imagining creating these shapes?

#

Do you want to be able to use a picture? Something you draw in the editor?

heady iris
#

If you specifically want to do math shapes, then you want a parametric equation: something that tells you x and y given another variable (usually called t)

#

you would sample the equation at a bunch of t values and create objects at them

orchid bane
#

is int? serializable by unity?

leaden ice
latent latch
#

Can make your own nullable type if you want

leaden ice
acoustic sinew
#

I'm using this to detect if the player is touching the ground. However, when the "isGrounded" never goes false even after the player jumps and is not close to the ground. isGrounded = Physics.Raycast(transform.position, Vector3.down, groundCheckDistance); Should I be using a collision check instead of raycaster?

marsh mesa
#

it might be touching some sorta trigger collider

#

or the player's collider

#

you can use layermasks to prevent that from happening

acoustic sinew
#

Oh, I do have a capsule collider at the players feet

marsh mesa
#

yeah, its probably touching that

#

are u familliar with layermasks?

acoustic sinew
#

I am not

marsh mesa
#

Should i explain, or will u look it up on ur own?

acoustic sinew
#

I can look it up lol

marsh mesa
#

Oki then, hope that helps!

acoustic sinew
#

It certainly does, thanks

marsh mesa
#

Its the first time i got this error lol

#

seems like i accidentally made some number go beyond its limit?

#

am i getting it right

#

and i have no clue what the heck AABB a is, does anyone know?

acoustic sinew
#

So LayerMasks is the reason why I should be using different layers with all of my gameobjects

marsh mesa
#

doesnt mean you have to use a diffirent layer for every object, its good to generalize

acoustic sinew
#

Oh boy do I have a lot to edit lol

marsh mesa
#

by the sounds of it, you are making a platformer, right?

#

and you want most of the objects with colliders to be considered ground

hard viper
#

layer masks are really useful

marsh mesa
#

ikr

acoustic sinew
#

Nah, I'm making an FPS shooter. But I don't want my character to be able to jump again or move if they're already in the air

marsh mesa
#

oh

hard viper
#

I have different categories for layer masks. With layer masks, you want the collision matrix not to have two layer masks that are identical

marsh mesa
#

but yeah, regardless, you can just give all the things that u should not jump off a layer separate layer

#

or do the opposite, make the layer only for ground stuff

acoustic sinew
#

Do layer orders matter?

hard viper
#

layer masks I have in my game: Terrain, Enemy, Entity, Player, CameraSpawner, CameraDespawner, EntityIgnoreEntity, EntityIgnorePlayer, SolidEntity, OnlyTouchEntity…

marsh mesa
#

if all the non ground objects have triggers, not colliders, you can just use 1 line to ignore triggers in your detections

hard viper
#

sorting layers tell you how sprites render on top of each other

acoustic sinew
#

Ahhh, okay

hard viper
#

a layer mask as a 32 bit integer. Each bit (0 or 1) correspends to if you are checking for a specific layer collision

acoustic sinew
#

So a layer "Concealment" can be any where in the layer list and bullets can pass through it as long as I call it properly

marsh mesa
#

i didnt know that, geez

#

that would've saved me so much headache

hard viper
#

so if terrain is layer 1, and player is layer 5, a layer mask of 000…00010001 might mean we are looking for objects in either Player or Terrain layer

latent latch
#

basically a bitwise enum

acoustic sinew
#

0_o

hard viper
#

there’s a little inaccuracy in my explanation because of layer #0 etc, but that is the basic idea

#

this way you can do bitmath.

marsh mesa
#

I had so much headache with detecting specific layers, and all that time i could've just used integers

marsh mesa
#

you can make certain layers just not collide with each other

acoustic sinew
#

This just made my life easier cause I was wondering how I was gonna do that

hard viper
#

So let’s say I want to make a layer override to allow a given entity to actually ignore the player now. I could get a layermask for player (0000…001000), then say: excludelayers |= playerMask

marsh mesa
#

i mostly used layermasks for certain specific lines of code, so i didnt have to deal with the matrix

hard viper
#

or stop exculding player by excludeLayers &= ~playerMask

hard viper
marsh mesa
hard viper
#

collision matrix makes the physics system automatically not check for collisions between different layers

marsh mesa
#

i have my reasons not to use it

hard viper
#

which is much cheaper

#

you should use it. and then you can add overrides to specific colliders

#

but if you use the collision matrix, you don’t need to specify a bunch of specific overrides for every single collider you make

marsh mesa
#

hmm

#

i guess i'll look into it

hard viper
#

you could avoid collision matrix, and just put layer overrides

#

but that’s just a lot more work in setting overrides

marsh mesa
#

I usually dont need objects to straight up ignore some colliders, i usually use em to check if thats the specific collider im looking for

hard viper
#

ignoring a collider is cheaper, because the physics system doesn’t need to start sending callbacks

marsh mesa
#

yeah but then my game wouldnt work in the way i want it to

hard viper
#

your collision code should almost always ALSO check for layer when handling collision

#

but for example, my player has no business colliding with a camera spawner.

#

I don’t even want to compute that collision. and i don’t want to deal with that callback being called OnTriggerStay for no reason

marsh mesa
#

ig i'll look into that, cuz i do have some cases like that

hard viper
#

in general, you want to avoid collisions between layers that have no business being involved with each other

#

mario’s fireballs do not need to check contact with mario, at all.

#

boos don’t need to check collision with ground… at all.

#

so instead of having a collision, and telling it to specifically ignore in the callback… just don’t have a collision

acoustic sinew
#

I there an easy way to mass select objects?

heady iris
#

you can search for objects with a specific component on them

#

t:Foo will find every object with a Foo on it

acoustic sinew
#

I mean in the editor so I can change their layer

heady iris
#

you can do that search in the hierarchy

hard viper
#

sure. and ALSO check the layer in the collision callback.

gleaming imp
#

I'd everything back to normal

acoustic sinew
heady iris
#

That syntax works in both the project view and the hierarchy

#

You can then ctrl-a in the hierarchy

hard viper
#

btw there is a good plugin I use to give constants for layers

heady iris
#

i just did that manually lol

#
using UnityEngine;

public static class LayerMasks
{
    public static int entityLayer;

    public static LayerMask entityMask;
    public static LayerMask arenaMask;

    [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterAssembliesLoaded)]
    static void Init()
    {
        entityLayer = LayerMask.NameToLayer("Entity");
        
        entityMask = LayerMask.GetMask("Entity");
        arenaMask = LayerMask.GetMask("Arena");
    }
}
hard viper
#

it basically lets you make a class called Layers and Tags with machine constants for individual layers, layer masks, and tags

heady iris
#

automating it is probably smarter...

hard viper
#

just download a package lol

#

It makes your code look like:
if (collision.gameObject.layer == Layers.PLAYER) {

#

or collider.excludeLayers |= Layers.TERRAIN_MASK | Layers.PLAYER_MASK

#

which also makes it super easy to find code that depends on specific layers

heady iris
#

huh? what then?

acoustic sinew
#

Well adding "LayerMask.GetMask("Ground")" to my raycast has now broken my player movement completely.

#

Maybe this means I should finish watching the tutorial

devout solstice
#

how could i check if a file is in the assets without throwing a error if it isn’t

#

i cant assign the file to a variable because if it isn’t in the assets there’s no file to assign the variable to, and it won’t detect the type

#

a that obv means i can’t just put the type into a if statement and call it a day because well same issue

thick terrace
#

i'm guessing you mean, how can you check if a C# type is available from a script that may or may not be in the project?