#archived-code-general

1 messages Β· Page 216 of 1

soft hare
#

sorry blanking

hybrid turtle
#

Input.GetKeyDown and Input.GetKeyUp() based on the scene

soft hare
#

this is right/

#

if (gameObject.CompareTag("Red") || collision.collider.CompareTag("Red"))
{
Destroy(collision.gameObject);
Debug.Log("Worked");

soft hare
#

man doesnt work how do i fix it

soft hare
#

where is the hint? @box

somber nacelle
barren dew
#

Hello how can i calculate the stopping point of a rigid body when an impulse force is applied to it

pastel halo
#

how do you force an object to match the same rotation? I want my character transform to match the same rotation only on Y, but it keeps outputting a different value. When the character moves around and I "drag mouse to move" it works.

When I enter a mount then dismount (applies code below) it doesn't work. Can't seem to figure out why the stored value isnt being applied. is it a specific rotation type?

I want the "player parent world transform" to equal the "camera's forward world transform (y only)"

         var rot = Camera.main.transform.localRotation.y;
            activeUser.transform.localRotation = Quaternion.Euler(0,rot,0);
simple egret
#

localRotation is a Quaternion, that does not store rotations in degrees

#

So rot is not the Y rotation in degrees, thus you can't reliably treat it as such

pastel halo
#

ah that seems to be the first major problem. How do you get/set the degrees of the objects XYZ?

#

transform.rotation is defined as a quaternion

simple egret
#

With localEulerAngles but note that one rotation can be represented with multiple Euler angles, which sometimes lead to inconsistencies

#

If you need to copy a rotation but only on a specific axis, you're better off getting a direction (like transform.forward), flattening that, and then re-create a rotation that looks towards this direction

#

With Quaternion.LookRotation()

leaden ice
simple egret
#

Code version of what I said yes

pastel halo
#

ah ok, that's alot more than i would've expected, but that does make sense. i def used that project on plane for clicking in the world

#

awesome thanks, i'll give that a shot

leaden ice
#

tis only two lines of code πŸ˜‰

pastel halo
#

cool it worked, thanks

hybrid turtle
#

@leaden ice whats the best way to design a script that while you hold down a key a timer is initiated and when you release the key the timer is paused

#

if the timer ever reaches zero reload the scene on top of the other

simple egret
#
if (Input.GetKey(YourKeyHere))
{
    timer -= Time.deltaTime;
}

if (timer <= 0)
{
    // timer expired. do stuff
}

In Update. Avoid pinging specific users

hybrid turtle
#

ok

#

thank you @simple egret

#

but timer has to be in increments of 1seconds

#

thats why I tried a coroutine with yield return new WaitForSeconds

simple egret
#

No, not really

spring creek
simple egret
#

If you need to display seconds then you can format it to get rid of the decimals

hybrid turtle
#

ok ok but even if i set my counter variable to be 30

#

then you are only ever subtracting Time.deltaTime off of it

#

like it needs to be like a 30 seconds real-time

simple egret
#

It will be

#

Delta time is the time between two frames, in seconds

hybrid turtle
#

ok maybe im just having a brain fart

leaden ice
#

The code is assumed to be in Update which runs each frame

hybrid turtle
#

yeah ofc then I guess it would have to be 30 seconds then

simple egret
#

30 seconds of continuously holding the key you want, as per your requirements

#

Release the key, and it'll stop subtracting delta time, effectively pausing the countdown

hybrid turtle
#

yes makes sense

#

thank you @simple egret

wispy wolf
#

Vector math eludes me to this day and this is hard to describe...

Say I have an axis represented by a vec3 location and a vec3 "forward". I also have two vec3s that can exist anywhere in the world. How do I find the angle between them from the persepective of this axis?

vagrant blade
#

You may need to draw out what you're trying to achieve. Or at least explain the context that this math is required since there's probably a different way to do it.

lean sail
exotic aspen
#

Hey folks. I'm running into performance issues with enemy-seeking via OverlapCircleAll calls. I've read in a number of places that the garbage collection can be an issue with this, and its recommended to use OverlapCircle instead. But that only returns the first collision. I'm usually having bunches of NPCs returning many hits, and am sorting through them looking for a hit on an enemy type. The nonalloc version says it is being deprecated soon. Am I missing something here?

lean sail
exotic aspen
#

Hmmm. I've not had much success trying to pass in an array for it to use.

exotic aspen
#

Yeah let me see here. One moment please.

#

So for example I see this defined in the code as an overloaded option: public static int OverlapCircle(Vector2 point, float radius, ContactFilter2D contactFilter, List<Collider2D> results)

#

I try to call it as such: Physics2D.OverlapCircle(critter.transform.position, ENEMY_SEARCH_RADIUS, LayerMask.GetMask("Hand Grabber"), allCollisions);

#

where: List<Collider2D> allCollisions = new List<Collider2D>();

#

But its complaining that allCollisions isn't a float.

quaint rock
#

use the one that has a array of collider2d for a result arg

lean sail
quaint rock
#

pre allocate that array

exotic aspen
#

Hmm. I see how do I change a layer mask into a contact filter?

quaint rock
#

just construct one

#

its a struct you can just make a new one that set up what you care about on it

exotic aspen
#

Ahh ok. Hadn't touched that object type before. Thank you let me give it a shot.

quaint rock
#

if you are calling this allot the list or array you pass in, keep that as a field on your class and keep reusing it

exotic aspen
#

Yes I anticipate reusing the same List so as to never garbage collect.

quaint rock
#

with a list it still might GC or do a copy

#

but only when list expands past its capacity

exotic aspen
#

:nod: I'll keep an eye out for that. At the moment its being called 500 times a frame for the AI to do things and its just way too much.

#

I had considered changing up the architecture of my NPCs. Currently they all exist on the same layer with a rigidbody and collider for physics purposes. Then on the prefab I have a child object with its own circle collider for engagement finding purposes. At the moment all the NPCs have the same one so I end up wasting a lot of time sorting through it. But if I gave each NPC type its own layer... that would cut down on it some.

quaint rock
#

500 times a frame seems exceesive

#

is this because of many many npc's?

exotic aspen
#

Well for 50,000 NPCs that spread it out over the course of 1 second.

quaint rock
#

does the work need to be done every frame or can you do so many per frame and have it take a few for a total update

exotic aspen
#

Yeah I'm spacing it out over time.

quaint rock
#

either way yeah pre allocated arrays or lists and reuse them

exotic aspen
#

Every update() call of the manager only processes a block of AIs.

#

I'm still learning if the physics2D hit of adding more layers is better or worse than just sorting through lists.

#

I've been disapointed at how slow the rigidbody physics is on mobile just for top-down NPCs moving around a 2D environment with no collisions taking place except for gravity on the floor.

night harness
#

@exotic aspen May be a really silly question, But are you being nitpicky with your Physics Matrix? At this scale you want to be ensuring your only hitting what you need to be

exotic aspen
#

I found that adding a couple of layers to the matrix increased the movement physics calcs enough to make 1 NPC consume 30fps on its own.

#

So I reduced the matrix to the bare minimum.

#

Older Android devices seem better at looping through dumb lists than physics calcs. I may go and screw with the iterations and stuff in the model settings. I don't need anything fancy at all here. Just stuff moving on the floor. I don't even process body on body collisions at this point.

#

That did the trick. Thanks for the help!

#

Now to profile away.

night harness
#

Also, Out of just general curiosity, You mentioned your game is top down 2d. Do you need to be applying gravity?

exotic aspen
#

So from all my reading you don't ever want to use setposition on things to move them around. You want to use physics for general movement along the floor.

#

That entails having Physics2D apply gravity on the rigibody down onto the surface for friction.

#

Not that I did anything in particular to make it work. Its just the default of how things move around.

quaint rock
#

no clue what type of game you are making, but nearly everytime i have worked in top down 2d or isometric i just directly took control of the transforms over using physics

exotic aspen
#

Every Unity tutorial or game design course I've observed has called out never to use SetPosition, always use MovePosition.

#

And MovePosition involves physics.

void basalt
night harness
#

I only mentioned it because if your NPC's aren't actually moving up and down (and even then) you probably don't even need to collide with the floor

quaint rock
#

or if this is a context where you even need the physics system and applying forces at all

#

really depends on the type of game

exotic aspen
#

So if I turn off the rigidbody material type and apply a force, the objects just fly off the map. They never slow down.

#

I don't believe the A* system I'm using allows you to setPosition anyways. Hmm.

night harness
#

rigidbody material type?

exotic aspen
#

yes so my NPCs have a Ridigbody2D component, and in that is a Body Type.

void basalt
#

setting a rigidbody's position/orientation manually will not give you what you want.

exotic aspen
#

Yes the A* Pathfinding Project asset on the store has various steering types.

#

But all seem physics enabled from what I've seen.

#

Going back a moment, I've read multiple times that you never put a 2D collider on a game object that lacks a rigidbody, and you never move a rigidbody with setPosition. Hmm.

quaint rock
#

sounds like more complication then is needed is being added somewhere

night harness
quaint rock
#

like have done my own A* and Steering, and if i want pathfinding never had to bring applying physics forces into it

exotic aspen
#

How many NPCs do you typically support?

#

I like the A* Pathfinding Project because it uses ECS and is multithreaded.

quaint rock
#

well i multithreaded my own

#

though for very large npc counts going to 1 destination A* actually sucks

#

since its a 1 point to 1 point type thing, not a many to one like other approaches

void basalt
#

@exotic aspenAgain, don't know what you've done/tried, but it sounds like you might be trying to recompute the path every frame. You want to rarely recompute, and just interpolate along the path that it already knows

exotic aspen
#

The Pathfinding Project itself does not recompute every frame. It is incredibly sophisticated. The pathfinding CPU usage is nonexistent in my profiling.

#

Its just the physics hits getting me at the moment. And I appreciate you challenging my approach here to consider something different.

quaint rock
#

and why does it need the physics forces? is that due to a machanic you want or so they can bash into and push stuff in the world?

void basalt
#

manually depenetrating them would probably be a lot easier on the CPU

quaint rock
#

like once you got your path, especially in 2d on a plane, its just a case of steering to look at your next waypoint and moving forward

exotic aspen
#

I suppose it was just how the asset was designed. It has an acceleration/deceleration as units begin moving and get to the destination. The more complex features it provides includes crowd steering and often-used path avoidance.

#

Truthfully I'm here to write a game, not an engine... so trying to not get too hung up on the more technical side of some of these mechanics.

#

In Torque2D I had written my own A* in C++. But I'm finding it harder to make that as performant in C# due to my skill level.

#

ECS is a bridge to far at the moment.

#

Thank you for the ideas. I'm going to consider it all here for a bitr.

void basalt
#

you might want to post your profiler results as well

#

if they absolutely need dynamic rigidbodies, and turning down the physics tickrate doesn't help, then you might be stuck.

exotic aspen
#

Well, right now the Physics hit is twofold. I've got all the CircleColliders eating up a ton of time. And then the Rigidbody stuff going on.

#

If I can solve the CircleColliders I may be fine here.

void basalt
exotic aspen
#

It is kind of impressive how a modern Android/iPad is 50,000x faster than one just a couple years old heh.

quaint rock
#

its not that much faster

exotic aspen
#

Well a blank tilemap with nothing going is 60fps with 10% remaining frame time on say a Samsung Galaxy Tab from 2019. Or a Kindle Fire HD from last year. Its at 60fps with 95% remaining frame time on my iPad, and that is with bump mapping, 2D lights and shadows.

#

A single 2D light will reduce most of these Android devices by 30fps. Its incredible. Must be some missing hardware support.

quaint rock
#

the cost of a light varies greatly

exotic aspen
#

At the moment I have settings to enable/disable the lights, the shadows and swap all the materials with non bump mapped versions.

quaint rock
#

depends on if you are in deferred or forward

#

in forward the cost of the light is re-rendering anything it hits

exotic aspen
#

By default I believe URP is forward?

quaint rock
#

in deferred you pay for how many pixels are lit

#

so it can handle shittons of small lights, but struggles with large ones more then forward

exotic aspen
#

Well, just a single 64px sized light is enough to crater most Android devices from what I've seen. But my iPad can handle hundreds without an issue.

#

I just don't have enough experience yet to really dig into the render pipeline and sort out why that is yet.

#

Well that's odd. Shouldn't forward vs deferred show up here?

spring creek
# exotic aspen I like the A* Pathfinding Project because it uses ECS and is multithreaded.

Do you mean Agents Navigation? A* Pathfinding Project (frim aron granberg) does not use ECS. It is explicitly gameobject based. I have spoken with Aron extensively about implementing it into ECS and there are a lot of of work to integrate the two. I have everything but RVO working in it

Agents Navigation from Lukas Chedosevicius was made in ECS and works with both ECS and gameobjects

exotic aspen
#

I must have been mistaken, one of the release note sections mentioned ECS components on the Follower AI when he moved it to using the Burst Compiler.

#

In any event, the pathfinding computation is not a bottleneck in my game environment. While it is perhaps a bit heavy of an asset for what I need, it works and so long as the rigidbody physics don't bog me down I'll probably stick with it.

#

Really cool other asset there. Thanks for posting about it.

spring creek
#

Oh it is certainly great. I just had to stop using it because of the lack of integration with ECS. things MAY have changed, this was like 8 months ago that I tried.
You can talk to ph0t0n at the TurboMakesGames discord about the journey to RVO in A*pfp haha

#

Ah yeah, can't link servers.
Well, it is searchable

quartz folio
exotic aspen
#

Thanks!

spring creek
#

Oh nice, thanks!

exotic aspen
#

This is the new seeker component using ECS I believe.

spring creek
exotic aspen
#

Yeah he's been porting over Beta features on a regular basis. So far so good.

simple sable
#

Hey everyone, quick question here.

I'm working on a system that uses a list of items from my game (scriptable objects), and that list has the tag [SerializeField] so that I can link my items in the inspector.
However, I was thinking... It would be kind of weird to have to remember to update that list manually every time I create a new item for my game. Is there a way I could make it more automatic?

unreal temple
#

Why does the first code block not work, when the second does?

// Cast for hits.
using var _ = ListPool<RaycastHit2D>.Get(out var hits);
Physics2D.BoxCast(
  origin: transform.Position,
  size: new(boxLength, beam.Config.Width),
  angle: transform.Rotation,
  direction: direction,
  distance: beam.Length - boxLength / 2,
  contactFilter: new() { useLayerMask = true, layerMask = layerMask },
  results: hits
);

// Process hits.
foreach (var hit in hits) {

This version does not return any hits.

static RaycastHit2D[] _hits = new RaycastHit2D[64];

// ...

// Cast for hits.
var hitCount = Physics2D.BoxCastNonAlloc(
  origin: transform.Position,
  size: new(boxLength, beam.Config.Width),
  angle: transform.Rotation,
  direction: direction,
  distance: beam.Length - boxLength / 2,
  layerMask: layerMask,
  results: _hits
);

// Process hits.
for (var i = 0; i < hitCount; i++) {
  ref var hit = ref _hits[i];

This version returns hits as expected.

I tried to BoxCast version because BoxCastNonAlloc is deprecated (according to docs). But it doesn't seem to work? Or am I misunderstanding how to use contact filter?

hexed pecan
unborn elm
#

Didnt seemed to be able to get help in the begginer section so trying here instead:

I have a simple targeting system for my Ai in my 2d game it works fine for the first couple of targets but then its start rotate on both x and y axis.
Cant figure out what im doing wrong, feels like ive done the exact same thing before without problems.


private void HandleTurning()
    {
        if (target != null)
        {
            Vector3 targetPosition = target.position;
            Vector3 playerPosition = playerGameObject.transform.position;
            playerDirection = (playerPosition - targetPosition).normalized;
            playerGameObject.eulerAngles = Vector3.RotateTowards(playerGameObject.eulerAngles,new Vector3(0f, 0f,        WorldSpaceUtils.GetAngleFromVector(playerDirection)),50f *Time.deltaTime,50f*Time.deltaTime);
            WorldSpaceUtils.GetAngleFromVector(playerDirection)),1f*Time.deltaTime);
        }
    }

The the get angle function looks like this

    public static float GetAngleFromVector(Vector3 vector)
    {
        float radians = Mathf.Atan2(vector.y, vector.x);
        float degrees = radians * Mathf.Rad2Deg;
        return degrees;
    }
lethal vigil
#

When checking the profiler if it’s not directly naming a method or file how do I know what the spike is referring to

marsh wadi
#

when profiling it shows this code allocates on every call, but I verified I don't enter the if beyond the first time

pools is a Dictionary<GameObject, ObjectPool<GameObject>>

marsh wadi
lethal vigil
marsh wadi
#

frame debugger is for GPU stuff

vague tundra
#

I have an issue currently where it seems like Input.GetMouseButtonDown (or any input method) isnt working inside of a coroutine. Does anyone know if this is the case?

fervent furnace
#

I remember i had used Input inside coroutine but i forgot what those methods are
But the Input is updated at the rate as update, if your coroutine are not run as exactly same rate as update it may broken (i think any getkey functions should work fine but not down/up

vague tundra
#

Oh cool, thanks for the insight(:
I'll investigate further with that in mind

fervent furnace
#

Similar to signal change

waxen kayak
#

I'm making a multiplayer game with thooushands of objects in a single scene

#

what is the best way to to turn off far a way objects?

#

I assume checking distance for each of them would be terribly inefficient

#

I've been thinking about a chunk based system

#

2d world divided into sections, and then you wouldn't have to check that many objects

#

but how would I do that?

fervent furnace
#

This is spatial partitions
Btw there are multiple players and each players has their own field of view, idk if Unity provides such functionality but you can use physics system to archive this

hexed pecan
waxen kayak
#

I have logic that needs to be turned off

#

it only turns of visual or not?

hexed pecan
#

Yeah its only visual, you need something else then

waxen kayak
#

rendering isn't terribly hard on 2d

hexed pecan
#

Missed the 2d part

lethal vigil
#

This might sound weird but how do games still look smooth at 30fps. If I set my game to 30 it’s seems real choppy. Does changing screen resolution help with performance?

somber tapir
#

You get used to the fps. When you drop from 60 to 30 you notice a big difference but when you start with 30 and are used to it it's not that bad.

lilac elm
#

in my code i have a variable that i only wanna show in the inspector if the upgradeKind is custom. heres my code btw:

[System.Serializable]
public class modifier
{
    public enum ModifierType
    {
        Percentage,
        Divide,
        Normal
    }
    public enum KindOfUpgrade
    {
        MaxHealth,
        moveSpeed,
        Damage,
        fireRate,
        reloadTime,
        magazineSize,
        custom
    }


    public enum kindOfStat
    {
        positive,
        negative
    }

    [Header("modifier Type")]
    public ModifierType modifierType;

    [Header("upgrading")]
    public KindOfUpgrade upgradeKind;

    public string customUpgradeName;

    public float amount;
    
    [Header("is it gud?")]
    public kindOfStat stat;
    
}
somber nacelle
#

gonna require either using an asset like NaughtyAttributes or Odin Inspector which have that functionality built in, or writing some editor code that checks the state of your upgradeKind variable and draws/doesn't draw certain properties

lilac elm
#

thanks πŸ‘

feral holly
somber nacelle
#

do you have that package installed?

late lion
feral holly
#

Thank you guys, you're right! Including Unity.Collections from the package as an Assembly Definition Reference did the job :)

tepid river
#

hello again,
i have 2 cameras, one that renders the 3d world, one that renders a UI that is overlayed over the world camera.
I want to add an effect to the UI camera that makes it flicker a bit, to make it look "holographic"

for that i have a custom shadergraph which i want to apply as a URP Full Screen Render Pass, but i want to apply it only to the UI Layer/my UI Camera
i made an additional URP Forward Renderer (UI layer only), and added the custom shadergraph as a renderer feature to it.
I then added the second UI renderer to the URP render asset

but it doesnt work. only the features on the default renderer seem to be applied and the second renderer does nothing.
What am i doing wrong?

#

oh wait i might have solved it. my UI camera was set to render to the default renderer πŸ˜„

#

aaaaaah it works πŸ₯³

heady iris
#

I'm thinking about how to implement persistent status effects into my game. I would like for a status effect to be used in many situations:

  • Adding a flat amount to a unit's base health
  • Changing the elemental type of an attack
  • Doubling all damage taken
  • Making a unit flinch when it gets hit by electric damage

I'm thinking of using SerializeReference to build a status effect out of "effect parts". So, I'll have a bunch of small classes like this:

[System.Serializable]
public class BaseStatModifier : StatusEffectPart
{
  public BaseStat stat;
  public void ModifyMax(ref float maxValue);
}

A status effect will then look a bit like:

[System.Serializable]
public class StatusEffect
{
  [SerializeReference]
  public List<StatusEffectPart> parts;
}

The dilemma is how I should "attach" and "remove" these parts. One option looks like this:

public class Entity : MonoBehaviour {
  private Dictionary<BaseStat, List<BaseStatModifier>> baseStatModifiers = new();

  public void Attach(StatusEffectPart part) {
    if (part is BaseStatModifier baseStatModifier) {
      baseStatModifiers[baseStatModifier.stat] += baseStatModifier;
    }

    // MANY OTHER DOWNCASTS GO HERE
  }
}

That's going to be one long list of downcasts, and it'll be very easy to forget one.

Another option would be to make all of these dictionaries and lists public, and then make each StatusEffectPart responsible for adding and removing itself:

[System.Serializable]
public class BaseStatModifier : StatusEffectPart
{
  public BaseStat stat;
  public void ModifyMax(ref float maxValue);

  public override void Attach(Entity entity) {
    entity.baseStatModifiers[stat] += this;
  }
}

This would require a ton of stuff to be exposed in Entity, and I don't really like that either.

A third option is to just make a single gigantic class with tons of virtual methods:

public abstract class StatusEffectPart
{
  public virtual void ModifyBaseStatMax(ref float maxValue) { }
  public virtual void ModifyElementalType(ref DamageData damageData) { }
  // MANY MORE VIRTUAL METHODS GO HERE
}

The base class's methods would do nothing. I would then override them to make different kinds of effect parts actually do something. This would simplify the types a lot -- there's just one big StatusEffectPart list, and I ask every single part if it wants to do anything every single time.

I've done this in the past in a smaller game and it seemed okay.

But now, if an entity has 20 effect parts on it, it has to consult those 20 parts over and over -- every single time I need to calculate any value that can be affected by effect parts. I prefer calculating values on-demand instead of trying to correctly cache them, so that's going to be a lot of pointless function calls.

Y'all got any opinions on the matter? I've been thinking about this problem for a few days now and I'm still not sure where to go with it.

#

whew, big post

#

In short, I am weighing three options:

  • Many specific kinds of effects, sorted out with downcasting
  • Many specific kinds of effects, with lots of Entity internals made public
  • One big kind of effect, with lots of no-op virtual methods
#

This is a soulslike game, so there aren't going to be that many entities active at once.

leaden ice
# heady iris In short, I am weighing three options: - Many specific kinds of effects, sorted...

But now, if an entity has 20 effect parts on it, it has to consult those 20 parts over and over -- every single time I need to calculate any value that can be affected by effect parts. I prefer calculating values on-demand instead of trying to correctly cache them, so that's going to be a lot of pointless function calls.
On the contrary - you need to consult them only when the modifiers are added / removed. Calculate the new value and cache it.

heady iris
#

that would be easy for "pure" modifiers that don't care about any other game state

#

but an effect that halves damage when you're below 20% health would not be so simple

leaden ice
#

that's true but I think that would be a different class of thing altogether

#

most things would be cachable

#

that could be a separate list of things that are not cacheable

#

this is very hard to do in a completely general purpose way

heady iris
#

Yeah.

#

and I'm trying to make the Most Obnoxiously General Purpose Way here

tepid river
#

can someone tell me if it is at all possible to apply postprocessing to one camera in URP but not to the other cameras in the stack?
bc i cant figure out how

heady iris
#

very little about my game is actually explicitly defined in code. you don't have a health value; you just have a list of VitalStats

#

and the player is configured to enter the DeadState when their health vital reaches zero

#

that kind of thing

leaden ice
#

Yeah I have a similar system in one of my games

heady iris
#

Bridging the gap between code and data can be very fiddly

leaden ice
#

You could have that modifier separately subscribe to the health stat for example and dirty the armor VitalStat's cache when it sees the health change in a certain way

heady iris
#

right, everything has OnChange events (or could trivially have them added)

leaden ice
#

right so - the modifiers can/should have OnAttach/OnRemove callbacks and in that you can subscribe to the OnChange for health and just change its own internal state and dirty the cache when the health goes below/above the threshold

heady iris
#

i want to go back to making a settings menu

#

that was easy

leaden ice
#

I assume you can do things like VitalStat healthStat = character.GetVital(VitalType.Health);

heady iris
#

🫠

heady iris
#

Delicious serializable data

#

I will think about this some more. I’ve got lots of less complex stuff I can focus on for now

latent latch
steady moat
# heady iris I'm thinking about how to implement persistent status effects into my game. I wo...

Realistically, I would use more of a query approach. By example, if you are getting hit by something, then you query all the require modifier for the resolution of the damage. I feel that this would be the more flexible approach. What is even better, is that you would be able to use those modifiers for multiple system. By example, you might want to modify the damage your sword is doing base on the defense you have.

public class Entity 
{
  public void OnHit(...) 
  {
    var percentageModifier = GetPercentageModifier();
    var flatModifier = GetFlatModifier();
    var onHitModifier = GetOnHitModifier();

    float result = damage / (base + flatModifier) * percentageModifier;
    InvokeOnHitModifier(onHitModifier);
  }
}

heady iris
#

Yeah, that's roughly what I'd like to be able to do. Your example just asks for modifiers instead of passing a value around to be modified, but it's a pretty similar concept.

#

I'm having more trouble with deciding how GetPercentageModifier will work -- how it knows which effect parts to use

#

Does it just iterate over every effect part and see which ones implement a certain interface? Does it call a method on every single effect part? Do the effect parts add themselves to a list in advance?

latent latch
#

For like effects that trigger on hit, such as a meteor storm that has a chance that procs on a weapon, I have basically list containers that trigger delegates that conform to specific targeting information.

#

so I just need to check if a list is empty or not, not the specific effect type

steady moat
#

You could even do a MonoBehavior to implement the interface and reuse it everywhere.

latent latch
heady iris
steady moat
heady iris
latent latch
steady moat
latent latch
#

probably not the biggest problem to calculate all the modifiers, but it makes sense to just cache what you got when the effect is applied, and just remove it through events.

heady iris
steady moat
heady iris
#

it sounds like you're suggesting something like option #3 here -- the last code block I posted in the original post

#

where there's just a single abstract class with tons of virtual methods on it

#

(also, i need to run on errands, so i'll be gone in a few minutes. thanks for the suggestions, everyone!)

steady moat
#

You could even use generic

heady iris
#

Ah, so defining one part for each kind of data

#

Not for each thing that can be modified

steady moat
strong night
#

Hi there! I'm trying to do something and was hoping you could help. I'm coming from a Javascript/Java background so it's not always obvious with C# for me.

I'm trying to send event messages from my web app to the unity webgl.
To do so, I need to send a string. So I chose to send a Json as string:

{"Messages":[{"Type":"MOVEMENT","Payload":{"MovementType":"UP"}}]}

Then on the Unity side, I have this set of classes which define the json payload I send:

namespace Library.Scripts.Messaging
{
    [Serializable]
    public class UserMessage
    {
        public string Type;

        public object Payload;
    }

    public class UserMessages
    {
        [SerializeField]
        public List<UserMessage> Messages;
    }
}

My goal is to parse and convert from the Json string to a UserMessages object.

Which I should be doing by running

var messages = JsonUtility.FromJson<UserMessages>(actionJson);

However, the result is a bit weird as I'm getting the equivalent of:

{
  "Messages": [
    {
      "Type": "MOVEMENT",
      "Payload": null
    }
  ]
}

Why would my payload be null? I don't believe I'm doing anything wrong. I'm expecting the Payload to be deserialised as well.

latent latch
# steady moat This is possible with what I have shown. You simply need to add some event

Yeah, I mean it's probably not the biggest problem if it's only one player recalculating their stuff every time you hit something. But assuming you got like multiple abilities that's constantly dealing damage; that's quite a lot of calculating. So ideally, cache what you can, but when it comes to enemy defensives and other miscellaneous stats then that's something you've got to dynamically calculate against.

steady moat
#
//Refresh when needed to be
float cache = (base + flatModifier) * percentageModifier;
...

float result = damage / cache;
latent latch
#

Right, and just update it every time you add/remove to the modifier list. Looks good.

#

The other miscellaneous effects like doubling damage seems a little harder to group upon and wouldn't really fit in such a list, well, it would be just another variable of the calculation I guess.

#

Basically, if you can group the effect, then you get the benefit of caching, but if it's a unique calculation then it's another specific operation to calculate against when you deal damage.

#
Adding a flat amount to a unit's base health //Stat modifier group [flat]: health, damage, speed, ect
Changing the elemental type of an attack //Elemental table group: Unique modifier that's not grouped with stat modifiers; independent variable, calculate on hit
Doubling all damage taken //Extra calculation variable group: Unique modifier. Check when receiving damage and decide its precedence.
Making a unit flinch when it gets hit by electric damage //Extra effect when hit group; check the group when the unit is hit.```
still carbon
#

I'm creating a "context menu tree" of options via EditorGUILayout.Popup() (by specifying child options with the slash.) This works fine except the context menu looks like it's a straight Windows control - totally different appearance than the rest of the IMGUI controls (such as the dropdown created by EditorGUILayout.EnumFlagsField().) Does Unity have something with similar functionality that utilizes the normal IMGUI visuals?

crude creek
#

Hi! I was wishing to find a way to search between all the gameobjects in scene with certain tag, and add them to a list. But I'm very new in coding and I can't seem to find the way to do it right. Thanks!

rigid island
#

using tags is kinda slow well not really but depends how many times

crude creek
#

I don't really have to use tags, it can be any way to get certain gameobjects into a list

rigid island
#

explaining the use case would help

crude creek
rigid island
spring creek
crude creek
#

oh right! I dont know hoe I didn't think of that earlier, thank you very much!

wintry stone
#

I have a hinge joint (im trying to make a latern with a handle) that is a child of the player object how can i make the hinge joint swing with the player when the player is moving?

hexed pecan
#

Or attach the hingejoint to the player rigidbody, not sure what you mean

#

Or is the hinge between the handle and the lantern?

wintry stone
#

would i be able to than connect the lantern to the player with a fixed joint?

hexed pecan
#

Yeah you can put a joint between the player and the handle

#

Or manually move it to the player's hand with forces or rb.MovePosition

#

Joint probably simpler

wintry stone
#

im gonna try to make it with the fixed joint. But would the fixed joint be on the player or handle?

wintry stone
hexed pecan
#

See if it behaves differently, it might not matter

hexed pecan
# wintry stone ok im gonna try it out thanks!

One more thing, if you use fixedjoint, you probably want to set the mass scale/connected mass scale (depending on what object you add the joint to) to 0 or a very low number so that the lantern doesn't affect the player's physics

#

If your player rigidbody is kinematic then it should not matter

true bramble
#
public class Parallax : MonoBehaviour
{
    [System.Serializable]
    private class Background
    {
        public float xBound = 128f / 16f; // image resolution / unity units
        public float yBound = 64f / 16f;  // image resolution / unity units

        public float speed;
        public GameObject bg;

        private Vector3 camOffset  = Vector3.zero;
        public void MoveBg(Transform parent)
        {
            //Update the background position for both the X and Y axes\\
            bg.transform.position = new Vector3(
                (parent.position.x * speed) + camOffset.x,
                (parent.position.y * speed) + camOffset.y,
                bg.transform.position.z
            );
            //Check if the background has gone beyond the x and y boundaries\\
            float camBgOffsetX = bg.transform.localPosition.x;
            float camBgOffsetY = bg.transform.localPosition.y;
            //Is the camera at the xBounds? if so move the bg so that the camera doesnt see the edge 
            if (xBound <= Mathf.Abs(camBgOffsetX))
                camOffset.x -= camBgOffsetX;
            //Is the camera at the yBounds? if so move the bg so that the camera doesnt see the edge 
            if (yBound <= Mathf.Abs(camBgOffsetY))
                camOffset.y -= camBgOffsetY;
        }
    }
    [SerializeField] private Background[] bgs = new Background[1];
    void Update() { foreach(Background bg in bgs) bg.MoveBg(transform);} 
}

Is this a good way to do parallax bgs

#

Is there anything I could have done instead of that xBound part I feel like I can just find those from the sprite renderer

#

instead of manually putting them into the inspector

wicked wagon
leaden ice
wintry stone
ashen yoke
leaden ice
wicked wagon
hybrid turtle
#

hi is there any way to speed up the delay on SceneManager.LoadScene()

#

my goal is to when a timer finishes have another scene load in

#

but it has to be quite fast

#

ik there is an async function

somber nacelle
#

make smaller scenes. the "delay" is it instantiating all of your objects.

#

but yes, there is a LoadSceneAsync method

hybrid turtle
#

i cant really make them smaller

#

they have lots of things in them is my problem

heady iris
#

well, then it's going to hitch

hybrid turtle
#

yeah it does hitch

#

like what I was thinking is start LoadScene Async sooner before the timer ends

#

and stall it until the timer finishes?

#

will that resolve anything?

heady iris
#

It might reduce the delay, but there will still be a hitch as the objects are actually created

#

I am just breaking into additive scene loading myself, so I've been experimenting with this stuff.

#

Perhaps you can just put spawners in your scene that then instantiate lots of objects over time

hybrid turtle
#

yeah I was thinking about additive

#

but then id have to disable all the gameObjects

#

in the other scene that i dont want present

#

cuz i feel like the hitch really ruins the experience

spring creek
heady iris
#

I'm working on a soulslike with a "Game" scene that has singletons and other game-wide objects

#

and then many small scenes that load and unload as you enter and exit trigger colliders

#

(this still needs a lot of work)

hybrid turtle
#

oh god singletons

heady iris
#

I need to start testing more elaborate scenes

hybrid turtle
#

yeah like its huge

#

there is a lot of lag

honest bloom
#

hey guys is there a way to set the mouse position or cursor position in unity?

#

Im making old csgo style buy menu and I want to move the cursor to specified position

honest bloom
#

fuck...

#

i hate this new input system

leaden ice
#

In the old system you'd probably have to use a native plugin per target platform to make it work

#

go look at the examples in the docs for this

#

because that's not how it works at all

#

ok nvm they have no examples lmaop

#

but it'd be like:

// freeze
Rigid.constraints = RigidbodyConstraints2D.FreezePosition;
// unfreeze
Rigid.constraints = RigidbodyConstraints2D.None;```
heady iris
#

The constraints property is a combination of various choices

#

it's one of those enum flag situations

leaden ice
#

if you are freezing rotation you will need a little more complexity

heady iris
#

A | B | C

leaden ice
#

e.g.

// freeze
Rigid.constraints |= RigidbodyConstraints2D.FreezePosition;
// unfreeze
Rigid.constraints &= ~RigidbodyConstraints2D.FreezePosition;```
#

yeah but the first example I gave will break that

#

if rotation is frozen

#

second example will work

honest bloom
#

tell me one thing. I know it may be obvious but, can I mix two input systems?

pulsar holly
honest bloom
#

new and old

leaden ice
#

just set active handling to Both

honest bloom
#

YEEEEEEEEEEEEES

#

PERFECT

heady iris
#

So I suppose you could just use the new input system exclusively to move the mouse cursor

leaden ice
#

highly recommend just learning the new system though, it's pretty good

heady iris
#

hey that reminds me

#

I need to figure out how to implement gyro look

#

although, I'm just thinking about using this on the Steam Deck, which can already do that for you

leaden ice
simple egret
#

Yeah this piece of code is very wrong

leaden ice
#

in fact all of your if statements are doing nothing

#

that semicolon means "end the statement here"

heady iris
#

your code editor should be giving you warnings every time you put a semicolon after an if statement

leaden ice
#

so what you have is "if I'm pressing the key, don't do anything"

#

Same for this: if (Degrees == 0);

#

"if degrees is 0, do nothing"

simple egret
#

Plus it's in Start, so it'll only happen once

leaden ice
#

Didn't even see that lol

heady iris
#

an if statement will run the statement that follows it if the condition is met

#

; terminates a statement

#

and empty statements are legal

leaden ice
#

I was too distracted by the semicolons

heady iris
#
if (true);
#

this is a complete and valid if statement

#

it will have no effect on the following code

#
if (true)
#

this is not a complete statement

#
if (true) { Debug.Log("Hi"); }
#

This is a complete statement.

pulsar holly
simple egret
#

You'll have to do way more than removing the semicolons, really - seems like you need to learn C#

leaden ice
simple egret
#

!learn

tawny elkBOT
#

:teacher: Unity Learn β†—

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

pulsar holly
leaden ice
pulsar holly
#

I tried removing the semicolon, but nothing.

heady iris
#

well, of course not, because all of this code is still in Start

pulsar holly
#

It's still not doing anything.

simple egret
#

Remote eyesight access over the internet (REAOI) is not supported on this device
You need to post the code if you want to get help

pulsar holly
#

Here it is.

#

That's the code.

simple egret
#

Is line 20 meant to be execute only when the conditions in the if statements are satisfied?

#

Because that's not the case here

pulsar holly
#

How do I fix it?

simple egret
#

You did not answer the question

#

Assuming that means "yes"

#

Without braces { }, if statements will only take the next line as inside the if statement

#

So you need to enclose the lines 19 and 20 with braces

#

Wait that was mentioned already wasn't it

pulsar holly
#

It worked! πŸ˜„

loud stratus
#

Hey, guys! I have a question here. If I want my background music of my main menu scene to not play repeatedly after the load of another scene for example I want to go to options scene and I have the same backround music that is playing. So, I want that music to be played continuously. Is there a function to make it work without loading the music again and again?

simple egret
#

You can load the scene additively. Or, don't use a separate scene at all, and enable/disable the needed objects

loud stratus
simple egret
#

Yep

woven matrix
#

hey guys I need help using the navmesh link, I got a plaform that moves and I am trying to use the link betewn the surface were the player moves and the surface of the platform, were the platform starts in the game start the link works, but after the platform starts moving to the next stop it does not work anymore any help? thanks

hybrid turtle
#

hey guys I have an unassigned ref going while I switch scenes thats an animator

#

even though it is assigned in the other scene

loud stratus
#

@simple egret Hey! You said to use LoadSceneMode.Additive but for one reason when I have tried to click options on my game it was a mess, my MainMenuScene appeared in front of my options scene.

hybrid turtle
#

its assigned in this scene that sceneManager loads

#

but on load it still says it's null

#

I have a transition in between

#

which I think may be the cause though

simple egret
#

You'll need to disable the objects you don't need to see

loud stratus
#

Oh, ok.

simple egret
#

Which brings back my second point, you probably don't need a separate scene for this. It'll be easier to manage with two canvases you dynamically enable and disable from the code

loud stratus
#

Oh bro I have made already the scene 😦

#

I will give it a try to find something out and to make that happen.

#

@simple egret Hey! I have deactivated the canvas of my main menu scene and now I have to deactivate listener because there was added a second listener from the main menu scene to the current scene. So, check what I did for that.

{
    if (!isPressed)
    {
        SceneManager.LoadScene("OptionsScene", LoadSceneMode.Additive);
        canvasMainMenuScene.SetActive(false);
        Debug.Log("The options scene is loaded!");
    }
}```
simple egret
#

A second listener? I think you're trying to (wrongly) cram all the code that fiddles with UI into one script

#

It's alright to separate logic into multiple scripts!

#

Your UI Manager should not be on the options scene. If you use that to manage the visibility of the menus, then it should be there once across the entirety of the loaded scenes, with other scripts (that react to a button press for example) calling methods on the UI Manager

loud stratus
#

Ok!

simple egret
#

That way, when you disable the button, there's no risk of the LoadOptionsScene to be executed multiple times, since the Button component is disabled

#

You can look into the singleton pattern if you want easy access of your UI Manager class from anywhere

loud stratus
#

Yes, but if I need this UI manager for other functionality of my Options scene? Do I have to use separate scripts? Personally, I don't like that way to tell you the truth of making different scripts for different things but if the situation is so hard to make it happen on one script then ok.

#

Singleton pattern?

latent latch
# heady iris I'm thinking about how to implement persistent status effects into my game. I wo...

Been working on something similar today, and going back to this I think you should split up the idea of your systems here. Simi had the idea how to manage your raw value stats, which there's very little reason in my opinion not to cache. Now, for stuff like making a unit flinch when hit by a damage type, or applying a value to your calculations when your player is low enough, I think that itself would be different lookups from different locations in your code.

Polymorphism for this stuff is pretty difficult I feel, and you can get away with a bit, but I think the idea of a superclass of triggers like your #3 example.

latent latch
# latent latch Been working on something similar today, and going back to this I think you shou...
public enum TriggerCondition
{
    ChanceToTrigger = 1 << 0,
    HealthThreshold = 1 << 1,
    WhileUnderStatusEffect = 1 << 2,
}

public abstract class BaseTrigger<SO> where SO : BaseTriggerSO
{
    public SO TriggerSO { get; private set; }
    protected Entity Entity { get; private set; }
    protected IDictionary<TriggerCondition, Func<bool>> baseTriggerConditionsDict;
  
    protected BaseTrigger(SO TriggerSO, Entity entity)
    {
        ...

        baseTriggerConditionsDict = new Dictionary<TriggerCondition, Func<bool>>
        {
            { TriggerCondition.HealthThreshold, () => { return HealthThreshold(); } },
        };
    }

    protected bool HealthThreshold() 
    {
        if(Entity.health >= TriggerSO.HealthThresholdNum)
        {
          return true;
        }
        
        return false;
    }
    
    //  Not too sure about the virtual idea for this; sometimes you want to pass in an extra
    //  parameter so either make another generic constraint or use derived-only call
    public virtual bool Trigger(Entity entity);
}```
Something similar to this idea for the trigger class of effects which should have an ownership of the entity.
placid pebble
#

Hello guys, I'm trying to understand why I have a mesh loaded into the memory in the profiler, even if I'm not using the mesh

#

I'm in a empty scene, empty project with just a mesh in the folders and still loading in the memory '-'

leaden ice
placid pebble
#

No it's in Assets folder, and no, it's not referenced, I created an empty project with just a mesh D:

leaden ice
#

the editor may have things loaded in for all kinds of reasons, like creating asset previews etc

placid pebble
#

ok I'll try

#

ty

elfin tree
#

Interesting, might do something similar, also considering using some item name or id, and just getting it from a list by id

latent latch
#

technically you could consider unique names as IDs

lean sail
#

hm I just so happen to be working on something similar, would the hashcode of a scriptable object be reliable as an ID?

latent latch
#

I've been just using the assetID and it seems fine. Someone was saying it's not reliable, but when you build the game the ID wouldn't change anyway.

lean sail
#

not sure what assetID is

latent latch
lean sail
#

oh thats editor only right? hm i might just stick with hashcode until i notice a problem. then ill try that

latent latch
#

It's ID specific to the SO instance, meaning that you'd keep them immutable

#

if you make new instances of SOs which you want to save (runtime), then you'd have a seperate ID probably along with the assetID

lean sail
#

this is just for premade items so wont create at runtime

hard viper
#

can you enumerate through a queue without dequeueing the whole thing?

#

I want to basically make one pass through a queue before I start dequeue/queue...

lean sail
hard viper
#

ty. just wanted to make sure it would work like that

unborn flame
#

when my player is in range of the npc the sqaure over the npcs head should appear, but it doesnt. It remains inactive in the hierarchy and it wont even manually let me make it active. here is my code and some screenshot: https://hatebin.com/qdnmobtspi

leaden ice
#

Update runs every frame

unborn flame
#

isnt it suspose to be in update because i am checking every frame to see if the player is in range

#

it should only be inactive if the first statement is not true

hard estuary
#

I often hide fields behind property getters to make it impossible to assign another value. It doesn't work well with structs, because as a side effect, it also blocks me from modifying the struct's content (since it's always a copied instance). In such cases, I can make fields public or create some extra methods to use those as a middleman between the class with such struct and other classes. Are there any other solutions worth considering?

pulsar holly
leaden ice
hard estuary
spring creek
#

So either way I assume this is way faster than you want

pulsar holly
#

Late reply, but it worked.

scarlet juniper
#

quick question, i have this code and when i enable the script i cannot play because of infitite loading but when i disable it it loads like normal. any1 knows what is causing this? https://hatebin.com/uetiytrhmn

spring creek
hard viper
#

question: when does the content of a coroutine up to its first yield evaluate?

#

is it on the same line that it is started?

scarlet juniper
swift salmon
#

hello, I build my own .dll and wanted to import it, but my unity kept crashing when importing. So I investigated and found out, that it is because I used anonymous classes as a middle product of a linq query. I want to find out if it's a known bug and report it if not. But I don't know where to check.

cosmic rain
swift salmon
timid kernel
#

Hello, I want to do something but I can't find a way for now and I never worked with curves, so it's pretty hard for me :
I want my gameObject (a boomerang) to attack the enemy as the graph shows :
starts from the player, then go on a curve through the enemy and continue until it reaches a set distance from the player, then come back to it's initial point following a symmetrical curve,
can someone please help ?

swift salmon
cosmic rain
#

Yeah. You'd think they're supported. Maybe it's something else?

swift salmon
#

and it stopped crashing

cosmic rain
#

How do you use the value?

swift salmon
#

I do not use it anyhow yet. It's an evolutionary algos dll that does not actually use the data, it only asks for some interface that is going to change it...

swift salmon
cosmic rain
cosmic rain
#

Maybe share the whole line of code.

latent latch
swift salmon
# cosmic rain Maybe share the whole line of code.

NEW:
var all = offsprings
.Select(p => new Scored<Scored<TIndividuum>>(p, p.Score))
.Concat(previousPop
.Select(p => new Scored<Scored<TIndividuum>>(p, p.Score * _previousPopSelectionBias)));

OLD:
var all = offsprings
.Select(p => (p, p.Score))
.Concat(previousPop
.Select(p => (p, p.Score * _previousPopSelectionBias)))
.Select(p => new Scored<Scored<TIndividuum>>(p.p, p.Item2));

#

the old one is not copied, I constructed it now retrospectively... but it compiled outside of unity just fine

timid kernel
#

thanks for your answers! I'll look into that (and ask more questions 😁) tomorrow

cosmic rain
swift salmon
cosmic rain
#

Ah, that might be the problem?
Doesn't it need to be a version that unity supports?

swift salmon
#

well... it started working just when I changed the anonymous class though πŸ€”

cosmic rain
#

It could be that the dotnet 6 treats the tuples in the old code differently

swift salmon
swift falcon
#

Is there a way to get the "[ExecuteInEditMode]" and "Update" to work in an Editor script?

#

I basically need to track if materials change while in the PrefabStage scene

#

Initially I thought I could just add a tracking script to the Prefab and then have it update in Editor mode but it doesn't allow me to add components in an editor script

cosmic rain
swift salmon
#

oh gotcha πŸ€” I will try using .NET standard and see

swift falcon
#

No because Update is a Mono event

#

On that, is "[ExecuteInEditMode]" redundant when you inherit from Editor?

cosmic rain
#

Yes.

#

I thought you were talking about a MonoBehaviour

swift falcon
#

No I'm like, in a bit of a limbo right now. I can't put a mono on the prefab, but I can't update in Editor

cosmic rain
#

Why can you not put a MonoBehaviour on the prefab?

swift falcon
#

It says it can't add script behaviour because it is an editor script

cosmic rain
#

Is it in the editor assembly?

swift falcon
#

Not sure what you mean by "Editor assembly"

cosmic rain
#

In an editor folder

swift falcon
#

Yeh yeh, I think that was the issue actually

cosmic rain
#

Then it is in the editor assembly

swift falcon
#

It wouldn't let me use "AddComponent" from a script that is in the Editor folder

cosmic rain
#

And editor assembly is not available at runtime.

#

Then take it out of the editor folder.

swift falcon
#

But I don't need this at runtime 😦 it's for the Prefab editing scene

cosmic rain
#

You don't need the Whole script or just the part that does the editor logic?

swift falcon
#

I see, so if I make an Editor script that just adds the component and that's outside, I call that and it's fine?

#

I thought Editor scripts had to be in that editor folder, thanks πŸ™‚

cosmic rain
#

If it's purely for editing time, might want to hook to some editor event instead, since Update is not available.

swift falcon
#

I would much rather go that route rather than relying on a monobehaviour yeh

swift falcon
#

I have a custom PrefabEditor window... I could call Update on the ChangeTracker from the OnGui in there? Dunkthink

cosmic rain
#

But you can put some editor logic in your regular script and surround it with an #if block

#

In the editor, there's EditorApplication.update delegate that you can subscribe to. Though, it's not called at regular intervals.

#

Look it up in the docs.

swift falcon
#

I assume it is similiar to the Mono Update execution in editor mode

#

Updates on changes, I'll take a look @cosmic rain Thanks, I appreciate it

cosmic rain
#

Perhaps.

swift falcon
#

If it does function that way then it's perfect

#

Basically if you update 1 prefab, it tracks changes and updates other related prefabs

#

Either way, multiple solutions there that will defo work, so I'll go have a play around πŸ™‚

swift salmon
spring creek
#

Is your collision matrix super strict? I just notice there are no conditions to setting isGrounded to true or false

#

Also, Translate doesn't respect collisions very well sometimes, so on complex surfaces, i could see that being an issue

#

Ok.

lean sail
#

transform.translate doesnt respect collisions at all

void basalt
#

yeah that collision code is really strange

#

and most likely the source of the jittering

lean sail
#

that isGrounded logic also wont really work when you add anything more than just a ground, like being next to a wall or hitting the roof will cause you to be grounded. your rigidbody may be trying to correct some things like the depenetration but this is just a rigidbody fighting your movement system

spring creek
lean sail
#

depending on how that base.TimeManager.TickDelta is calculated, you could probably teleport through walls with that code by lagging intentionally

proud juniper
#

In UI Toolkit, is there any way to preview nested documents in the editor without running your game? Ie I use a document per row in a scrollable list, it'd be nice to preview that ahead of time without having to run my game

proud juniper
#

Need to flip to project and use other UIDocuments

spring creek
lean sail
#

thats a really fragile solution, still there is everything else about it like using transform.translate with i assume a rigidbody

#

you probably need to project your movement along the normal of the surface they are walking on

proud juniper
swift falcon
#

Got a slight issue though with my code that if I drag over 2 overlapping prefabs it'll keep the material rather than it being a preview

#

Sorry code is ugly

rancid pond
#

I have a "collisionhandler" script which has unity events when some collision events happens. I have a public function which is assigned to eventhandler in inspector. But when collision happens, it is giving me
"ArgumentException: Object of type 'UnityEngine.Object' cannot be converted to type 'UnityEngine.Collider'."

#

why this is happening?

cosmic rain
#

Share the error details@rancid pond

cosmic rain
#

How are you subscribing to the event?

#

Wait. Nvm

#

Honestly, I'd use a simple Action there instead of a unity event. It just makes things complicated.

#

Also, try debug logging the value of other in the OnTriggerEnter/Stay.

cosmic rain
# rancid pond this is inspector

I feel like you can't really use unity events like that. It would try to pass the parameter that you have set in the inspector(None), wich I'm not sure what resolves to.

#

Probably a UnityEngine.Object, since that's what the error says.

#

The docs also mention that you must override the class type if you're using a generic unity event.

#

Basically you're digging yourself a hole by using it(the way you do)

rancid pond
#

KingTrigger funtion should be invoked with parameter "collider other" from event trigger right?

cosmic rain
#

No

#

It's registered in the inspector, so it would use the parameter from the inspector

rancid pond
#

ok got it.. thanks

fresh ingot
#

ok so i know how to fix it but why is this not allowed?

#

nevermind that didnt fix it lol

spring creek
fresh ingot
#

i figured it out its because i didnt specify that the barrack type is public

polar marten
fresh ingot
#

also fuck yeah gojira

fresh ingot
#

im kinda rusty on unity lol ive been doing only c++ and gamemaker things for the past few years

#

did it noww

lilac scaffold
lean sail
#

I dont see how u are running public IEnumerator RunGame() either, since you need a mono to run coroutines

lilac scaffold
lilac scaffold
lean sail
lilac scaffold
#

i cant really untill other stuff is ready

#

most of this game systems intertwine pretty heavily and to get a good idea if its working at least some form of gameplay needs to be working

lean sail
#

are you creating many instances of this SO?

#

you could use an SO which stores all those ints and floats like NightSettingsSO, then plug it into NightManager which you could make into a monobehaviour. NightManager would copy all the data from NightSettingsSO and then mutate it

lean sail
lilac scaffold
#

and i am still learning how UIToolkit works as its a bit weird rn

lean sail
#

It doesnt matter if it displays anything to the UI, your HourChange and PowerChange are already subscribed to by GameManager so it will debug something

delicate flax
# lilac scaffold Hey guys im looking for some opinions on my current code https://paste.myst.rs...

NightManager (or any manager β€˜type’) class being a scriptable object is a bit weird, as you generally don’t want SO to contain mutable data. It could maybe make sense to have a NightManagerSettings scriptable object, but again seems strange unless you need multiple settings objects.

Events in NightManager should be invoked using β€˜PowerChange?.Invoke();’ as that will handle null events.

probably not an issue, but conceptually it’s a bit weird that NightManager has β€˜RunGame’ and β€˜GameOver’, I would kinda expect that to be in the GameManager.

I’m wondering if GameManager and NightManager should be singletons, and all NightManager interaction should be proxied in the GameManager. It seems like you’re setting yourself up for a spaghetti mess if everything can access anything at any time.

Like β€˜gameManager.nightManager.HasPower = hasPower;’ in LightButton has me a bit concerned since light button is mutating really important gamestate directly, it not always a problem, but something tells me that in this game setting the power is a β€˜big deal’

Similarly, β€˜gameManager.powerDrainModifier = gameManager.powerDrainModifier + 1;’ this should probably be a method on GameManager. It could at least be simplified: β€œ gameManager.powerDrainModifier += 1; β€œ

lean sail
#

I was just about to make a similar comment about the LightButton script. You seem to be misusing public a bit much. If we unravel what gameManager.nightManager.HasPower is, your one single LightButton is now taking the entire game manager, and accessing its stored nightManager, then directly changing if you have power. Your LightButton script shouldnt have so much authority.

gameManager.nightManager.HasPower = hasPower; This is definitely something you dont need to update every single frame either, you can update it only when hasPower in LightButton changes.
Although your script doesnt even change hasPower so I dont know whats supposed to happen there

lilac scaffold
#

Most of the power stuff is coded by me so is 100% not working as intended i wasjust messing around

#

Only bit i really had help with was the general nightmaanger setup

#

And In theory there will be more than one night settings

#

because each night gets harder

#

Also other things i got from others in GMTK and Brackeys is that game amanger is "doing too much" rn others also confused about SO but it was suggested because its much easier to edit

#

so @lean sail @delicate flax do i just move the coroutine into GameManager or make a new nightManager thing and rename this to settings

night harness
# lilac scaffold most of this game systems intertwine pretty heavily and to get a good idea if it...

More of a subjective suggestion, But something thats really valuable for a gameplay programmer and/or designer is to recognize what is actually necessary for your minimum viable product (MVP). If you take some time to think there is probably a lot you can reduce from the mechanics and systems your making to do initial prototyping. you don't want to get tied up into spending a ton of time on systems that immediently get scrapped because the gameplay isn't feeling right on fundemental reasons

lilac scaffold
#

You cant have a fnaf game without basic things like the power system and Time

lean sail
# lilac scaffold so <@119616167894712320> <@244250475036147713> do i just move the coroutine into...

id honestly not even worry about using scriptable object yet until you need to make the night settings. NightManager can be a monobehaviour, but I cant exactly say where RunGame() should live since i dont truly know what its doing. I also havent played the game i believe u said u are trying to recreate
Since its affecting values related to the NightManager, you should probably keep it in there but give your scripts one defined goal. Like what is NightManager really supposed to do?

lilac scaffold
lean sail
#

Yea suddenly this is more than what it should really handle then

lilac scaffold
#

Rungame starts the timer for the night and also Starts the power drain and will eventually enable AIs.

lean sail
#

by the names of things, your night manager should only handle "Starting the night, ending the night".
Dying should go through your game manager, and a character getting into your office can be a simple trigger collider in the office. The office can notify the game manager that something got in

night harness
#

Honestly for a game like this it could all go into a single gamemanager

lilac scaffold
night harness
#

Everyone is going to have a lot of opinions

#

You gotta pick your battles when it comes to making good code. Personally in this case I think it's worth a lot more to you to make this work as fast as possible

lilac scaffold
night harness
#

You know the scope of the game so it's a lot easier to know what your going to have in it

lilac scaffold
#

im heavily mimicking how the original games worked

night harness
#

What do you mean by it's posed?

delicate flax
# lilac scaffold so <@119616167894712320> <@244250475036147713> do i just move the coroutine into...

Well I can’t tell you that there is a β€˜correct’ way to do this, it’s also hard to give good architectural advice, since the code is functionally incomplete.
But having the following might be a good idea, you have to decide that on your own.

// basically just a β€˜clock’ class, not even sure this needs to be a MonoBehaviour
NightManager
    public event Action NightOver;
    public event Action<int> HourChange;
    public event Action<float> PowerChange;

    public void RestartClock();
    public void Tick();

// Handle game state stuff, and expose needed methods for mutating game state
GameManager : MonoBehaviour
    public void UpdateModifer(int amount);
    public void StartNight();
    public void EndNight();
    
    private NightManager nightManager;

    void Update() {
        // check game state
        // tick nightManager
    }
night harness
#

also I might have missed bawsi suggesting it but for field variables (like HasPower, Power etc.) you want lowercaseUppercase

lean sail
lilac scaffold
# night harness What do you mean by it's posed?

so characters arent animated in a normal way they "teleport" and go into a different pose and then on their second to last they apear either in the office or at one of the 3 places you save yourself by flashing a light or shutting a door on them

night harness
#

nothing about that stops you from using trigger colliders if you wanted to do so

lilac scaffold
#

its hard to understand if u never played the originals and know what im trying to do

night harness
#

I know the game

lean sail
#

unless they appear for literally 1 frame, there is no issue

#

the only issue i could potentially see is if you update their positions so quickly that the physics stuff never runs

lilac scaffold
# lean sail the only issue i could potentially see is if you update their positions so quick...

the way i plan to do moving is have a base move time then when that hits zero based on the night number and individual AI difficulty they have a chance to move somewhere. i want to be able to set some "off rooms" that are not the main path. when they get to the door if it closes on them they wait for a random time then move back to one of the off rooms or the starting room. Some characters will be unaffected by the doors and will need to have a light flashed on them either at the front window or at the door. I think i explained this alright

dire marlin
#

Hi there,
I'm making a randomly generated maze-like game, but I want to add a monster chasing players. However since the maze is procedurally generated, i am not sure how to go about solving this. I have tried to make ai navigation paths in different rooms but nothing works, how can i solve?

lean sail
lilac scaffold
main shuttle
dire marlin
main shuttle
dire marlin
#

thank you!

lilac scaffold
formal wagon
#

Hey all, if I mark a method using [MethodImpl(MethodImplOptions.AggressiveInlining)], will it be in-lined while running the game in the editor? I've in-lined the FastModulo function here, though I'm not sure if the function showing up here when I run Deep Profile means that the editor hasn't inlined it. Does deep profile account for that sort of thing? If not, then how would I be able to verify that my function's been in-lined?

cosmic rain
sharp sun
#

I'm raycasting using the GraphicRaycaster on this ui for valid coordinates but for some reason it's never returning any objects, not even the background panels. Is this an issue with rendering the ui to a RenderTexture or is there something else I'm missing?

The texture resolution is 1920x1080 and the raycast is checking the coordinate (213, 947) (i checked with breakpoints to ensure it's at least checking the right position)

    private void Update()
    {
        UpdatePointer();
        List<RaycastResult> res = new List<RaycastResult>();
        PointerEventData ptrData = new PointerEventData(FindObjectOfType<EventSystem>()) { position = ptr.position }; // yes I know inefficient but im trying to get it to work
        raycaster.Raycast(ptrData, res);
        foreach (RaycastResult hit in res)
        {
            Debug.Log($"hit {hit.gameObject}");
        }
    }
leaden ice
sharp sun
#

It's for a VR game, so I want a custom interaction system where you tap the tablet

leaden ice
#

Why not just use a world space canvas

sharp sun
#

This way I can write a shader that uses the texture and renders other elements and effects on top of it

leaden ice
#

Alright well it's a bit unclear where ptr.position comes from as well as raycaster

sharp sun
#

raycaster is a reference to that graphic raycaster component, and ptr.position is just a vector2 that gets calculated every frame based on the ray intersection of the in-game "pointer" object and the tablet's screen.

#

It's just returning an empty list every time, it's bogglin' my mind

leaden ice
#

Oh nvm you said it

sharp sun
#

I'll probably wind up scaling it down to at least 720p for vr but im just tryna get the raycasts rn

amber berry
#

I'm having a problem with Unity serialization. I am trying to serialize an array of generic types, for the inspector. However, it doesn't work, and the answer I found was to create an empty inheriting class. This, however, is inconvenient for me, seeing as I'm using structs. Is there an alternative solution?

cosmic rain
#

Generic structs?πŸ€”

#

You could write a custom editor/inspector/property drawer if that's more convenient for you.

amber berry
#

A struct that takes in a generic, or wahtever one says.

cosmic rain
amber berry
cosmic rain
#

Ah, yeah. That's a generic struct.

amber berry
#

Alr

#

I looked at some documentation for "ISerializationCallback", though don't know if it'd work in my case.

cosmic rain
#

I'm not sure if that's gonna help with the inspector.

cosmic rain
#

Writing an editor script to draw the inspector.πŸ€·β€β™‚οΈ

amber berry
#

Alright, but how would I translate that to work for my generic type?

#

Because if Unity can't serialize it in the first place, why would it be able to in a custom editor script?

cosmic rain
#

Because you would define how to draw it.

#

You'd draw corresponding property fields(ui) for the struct fields

hexed pecan
amber berry
hexed pecan
#

Ah nvm, the issue is that it's not a concrete type, right

cosmic rain
#

Element is the generic type

hexed pecan
#

I know

amber berry
#

Here's my current architecture:

public class Grid_Definition : ScriptableObject
{
    public Matrix_Map<IGridTile> Matrix_Map;
}
[System.Serializable]
public struct Matrix_Map<Element>
{
    public Matrix_Row<Element>[] Matrix;
}
[System.Serializable]
public struct Matrix_Row<Element>
{
    [SerializeField]
    public Element[] Elements;

    [HideInInspector]
    public int Length
    {
        get { return Elements.Length; }
        private set {; }
    }
}
steady moat
#

You wont be able to serialized a generic type without specifying it. (Inherit from it and remove the generic)

amber berry
#

IGridTile is an interface.

cosmic rain
#

Honestly, I'm not sure there's a point in generics here.

hexed pecan
#

I think List<T> is the only generic that unity can serialize, and thats a special case

amber berry
amber berry
#

Why can't I write "Hm" πŸ˜„

cosmic rain
#

I'm sure tiles have something in common for them to make sense to inherit from a base class.

amber berry
steady moat
hexed pecan
#

Declaring the concrete class is just one linecs public struct Matrix_RowFloat : Matrix_Row<float> {}
But wait this is a struct

#

Can't inherit

cosmic rain
#
[System.Serializable]
public struct Matrix_Row
{
    [SerializeField]
    public BaseTile[] tiles;

    [HideInInspector]
    public int Length
    {
        get { return tiles.Length; }
        private set {; }
    }
}
amber berry
cosmic rain
#

A base tile

amber berry
#

Because my use of generic type, is that not only will I have "IGridTile", but also "IGridEntity".

cosmic rain
#

That you can inherit from to implement specific functionality

#

Sure, you can do the same with inheritance.

amber berry
#

So would I have to create an underlying, say "IGridElement" interface?

cosmic rain
#

Oh, but they would have to be classes I guess.

hexed pecan
#

Thats what im saying

steady moat
#

Do you really need them to be struct ?

cosmic rain
#

Why not use classes anyway?

steady moat
#

What is the scope we are talking

amber berry
steady moat
cosmic rain
#

In what way is it practical?

steady moat
#

It is usually for performance you use struct

amber berry
cosmic rain
#

In what way?

amber berry
cosmic rain
#

Why not?

#

What's the problem?

hexed pecan
#

You need a class if you want generics + serialization here

#

Because structs can't inherit so you can't make the concrete class

steady moat
#

Otherwise, you could always try to comeup with an other serialization method.

#

And give up Unity serialization

amber berry
steady moat
#

Like, use a .txt file

amber berry
steady moat
#

There is not a lot option here.

cosmic rain
#

I don't get the logic.
"I'm gonna sit on a cactus because it's convenient. How do I make it not hurt my butt?"

hexed pecan
steady moat
#

That would require class

hexed pecan
#

It is a class

steady moat
#

They wants to use a struc

cosmic rain
#

We still didn't hear the explanation of what exactly is practical about the structs vs classes?😁

thick terrace
#

you totally can serialize a generic type, that's an old limitation that disppeared a few years ago when they updated the serialization system iirc

hexed pecan
#

@amber berry It works fine for me

steady moat
#

So, you can do List<MyGeneric<float>> ?

#

Never been able to do that

hexed pecan
cosmic rain
#

It needs to be a serializable type though?

hexed pecan
amber berry
hexed pecan
#

Is Element an interface?

thick terrace
#

well, you can do it with SerializeReference, but it's a pain in the butt

steady moat
amber berry
hexed pecan
#

If you named it with the C# conventions (IElement) I wouldve seen that its an interface

amber berry
amber berry
#

The type that is Element in our case is an interface

cosmic rain
#

What matters is what type does the object you want to serialize have.

#

Not the declaration.

hexed pecan
#

SerializeReference is a game changer tho

hexed pecan
scarlet viper
#

Nevermind

#

I know now

thick terrace
slate trellis
#

is there a method that combines the properties of TryGetComponent<T>() and GetComponentInParent<T>()? For example TryGetComponentInParent<T>()?

leaden ice
fervent furnace
#
if((component=GetXXXX)==null){}
leaden ice
slate trellis
leaden ice
#

ok?

slate trellis
#

but still thanks for the notice

leaden ice
#

you did ask

slate trellis
harsh niche
#

I would like the timeline be able to have multi-scene references. I already have a GUID-component based reference system but how do I make this work for GameObject editor fields that I cant edit like the timeline. Any ideas?

slate trellis
#

how would I use it with a type referene? for example

Collider[] example = Physics.OverlapSphere(transform.position, 10);
foreach (Collider collider in example)
{
  if (collider.gameObject.TryGetComponentInParent<ExampleComponent>(out ExampleComponent ec))
  {
    // do smt
  }
  else
  {
    // do smt else
  }
}```
fervent furnace
#

change it to extension method

#
static bool TryXXX(this Gameobject go)
harsh niche
#

Do note that extension methods also need to be inside of a static class, so I often write a separate class for the type I make extensions named after that type , eg.

static class GameObjectExtensions { }
slate trellis
#

2 errors:

  1. cannot inherit Monobehavior (to use GetComponentInParent<T>()) as it isn't a statc class
  2. GetComponentInParent<T>() needs an object reference as it is inside a static function
#

I am really bad in terms of Static, if it doesn't show. I tried to search it up and it didn't help my confusion

leaden ice
#

it's an extension method

#
public static class ComponentExtensions {
  public static bool TryGetComponentInParent<T>(this GameObject g, out T result) where T : Component {
    result = g.GetComponentInParent<T>();
    return !System.Object.ReferenceEquals(result, null);
  }

  public static bool TryGetComponentInParent<T>(this Component c, out T result) where T : Component {
    return c.gameObject.TryGetComponentInParent<T>(out result);
  }
}```
slate trellis
#

ah

#

makes a lot more sense now

#

thanks. I will do more research for extension methods and static fields

leaden ice
#

there are no static fields here

slate trellis
#

I don't know the terms T-T. In general to whatever static refers to

leaden ice
#

static means a few different things in different contexts. In C# it's generally marking something as being related to a class itself as opposed to a specific object instance.

harsh niche
#

I also recommend learning the terms since they're quite important for communicating!

slate trellis
harsh niche
#

Field refers to a class member variable btw.
The reason Praetor said they weren't static fields was because they're static functions.

slate trellis
harsh niche
#

I would recommend preferring English sources whenever possible

slate trellis
leaden ice
scarlet viper
#

i wonder what it does

#

ohh thats some destructor

latent latch
#

the deconstructor?

eager fulcrum
#

Hey, is it possible to save List<byte[]> using JsonUtility.ToJson? Cuz im having some problems with it

leaden ice
#

JsonUtility doesn't support nested lists/arrays

#

because it uses Unity's serializer which doesn't support nested lists/arrays

eager fulcrum
#

i see

#

so how can i convert it to json then?

#

what would be the easiest work around

leaden ice
#

change the structure or use a different serializer

#

You can do something like:

[Serializable] public class MyClass {
  public List<DataHolder> data;
}
[Serializable] public class DataHolder {
  public byte[] bytes;
}

public List<MyClass> example;```
eager fulcrum
#

alright, thanks!

rough orbit
#

Hey So i'm doing the tank game that would part of the unity tutorial and i was trying to modify the round ending screen where if the timer ends and no player is destroyed then it would go to a Draw state and end the round with no points given to no player. But i'm having diffcultly on how to execute the code, can someone help me with it.

#

private IEnumerator RoundPlaying()
{
EnableTankControl();

    m_MessageText.text = string.Empty;
    Being(Duration);

    while (!OneTankLeft() && remainingDuration > -1)
    {
        yield return null;
    }
}


private IEnumerator RoundEnding()
{
    DisableTankControl();
    m_RoundWinner = null;

    m_RoundWinner = GetRoundWinner();

    if (m_RoundWinner != null)
        m_RoundWinner.m_Wins++;

    m_GameWinner = GetGameWinner();

    string message = EndMessage();
    m_MessageText.text = message;
    

    yield return m_EndWait;
}


private bool OneTankLeft()
{
    int numTanksLeft = 0;

    for (int i = 0; i < m_Tanks.Length; i++)
    {
        if (m_Tanks[i].m_Instance.activeSelf)
            numTanksLeft++;
    }

    return numTanksLeft <= 1;
}

private TankManager GetRoundWinner()
{
    for (int i = 0; i < m_Tanks.Length; i++)
    {
        if (m_Tanks[i].m_Instance.activeSelf)
            return m_Tanks[i];
    }

    return null;
}

private TankManager GetGameWinner()
{
    for (int i = 0; i < m_Tanks.Length; i++)
    {
        if (m_Tanks[i].m_Wins == m_NumRoundsToWin)
            return m_Tanks[i];
    }

    return null;
}


private string EndMessage()
{
    string message = "DRAW!";

    if (m_RoundWinner != null)
        message = m_RoundWinner.m_ColoredPlayerText + " WINS THE ROUND!";

    message += "\n\n\n\n";

    for (int i = 0; i < m_Tanks.Length; i++)
    {
        message += m_Tanks[i].m_ColoredPlayerText + ": " + m_Tanks[i].m_Wins + " WINS\n";
    }

    if (m_GameWinner != null)
        message = m_GameWinner.m_ColoredPlayerText + " WINS THE GAME!";

    return message;
}
fervent furnace
#

!code

tawny elkBOT
rough orbit
prime sinew
rough orbit
# prime sinew what are you having difficulty with?

I'm trying put in a code where it would go to draw and ether tank would earn a point and than it would get to the next round, the problems is that, I don't know what point do i have to put in to call the draw method, i try using GetRoundWinner to get a draw but it didn't work and i tried using OneTankLeft to call a draw but that wouldn't work. So i'm asking what am i doing wrong on this code where i would call the draw method

lament raft
#

so my function need a string list

#

why cant it get it

#

oh

#

wait

vagrant blade
#

You have to pass in an array of strings.

#

You're passing in two separate single strings as unique parameters.

lament raft
#

ok how do i do it

fervent furnace
#

you need params in this case

vagrant blade
#

Make an array of strings πŸ€·β€β™‚οΈ

lament raft
#

i will just look it up

vagrant blade
#

You either hardcode it, or you expose it to the inspector via [SerializeField] string[] myArray and type it out there.

vapid condor
lament raft
#

i fix it

inland arrow
#

hey what's with this:
Instantiating mesh due to calling MeshFilter.mesh during edit mode. This will leak meshes. Please use MeshFilter.sharedMesh instead.

somber tapir
inland arrow
#

I do want to instantiate the mesh. if I use the sharedMesh, it will write my changes back to the original file.

#

permanently breaking it

vapid condor
inland arrow
#

can't it GC the temporary mesh when it's not being referenced anymore in the scene?

lament raft
main coral
#

Hello, maybe someone here can help me. I use Network Animator to synchronize the animations. I added the Network Animator to the Animator, as a host it works without any problems. I see the synchronization on the client and the host. But when I run with the client, the position is synced but I don't see the animation.

main coral
#

OK sorry!

hard viper
#

you posted your query in code general, beginner, and advanced. pick one and delete the others

cobalt apex
#

I've got some strange behaviour with my particle system, especially with simulating the particles and was wondering if anyone has encountered something like this. I've got a particle system that needs to be pre-simulated a bit. The actual simulation part is no problem at all, but the behaviour i'm encountering is still very strange. The first time I load up the game in the editor, the simulation is pretty much instant. However, when I exit playmode and start up the game again, without having touched anything, the exact same simulation is taking upwards of 60-70 seconds. I'm suspecting it has something to do with editor caching, but i'm honestly out of ideas at this point. Has anyone encountered this before? Hopping between branches also seems to solve the problem, but only once as described above..

leaden ice
#

you have to use Destroy to destroy Unity objects

#

anyway the error tells you exactly how to fix it

inland arrow
#

yea i think ive dealt with this before and just forgot

#

it's this whole thing again.

#

        Vector3[] vertices = sourceMesh.vertices;
        Vector3[] normals = sourceMesh.normals;
        Vector4[] tangents = sourceMesh.tangents;
        Vector2[] UVs = sourceMesh.uv;
        int[] triangles = sourceMesh.triangles;
        mesh.name = sourceMesh.name;```
#
        mesh.normals = normals;
        mesh.tangents = tangents;
        mesh.uv = UVs;
        mesh.triangles = triangles;
        mf.sharedMesh = mesh;```
#

i wish there was just a mesh.clone().

leaden ice
#

there is

#

Instantiate(someMesh)

inland arrow
#

oh, okay, let me try that

#

i thought it only worked for gameobjects(read: prefabs)

leaden ice
#

You thought wrong

#

Instantiate works for basically any UnityEngine.Object

inland arrow
main coral
#

OK guys, I found the error.

#

You should go through the documentation from top to bottom and not start in the middle.

#

xD

vapid condor
naive swallow
vapid condor
#

i know, but i dont think he did that on purpose

spring creek
vapid condor
#

to write it like that yes, but i dont think he wanted to write them like that

spring creek
vapid condor
#

i would not choose params in this case for readability reasons

#

but it depends heavly on the context, i dont rly know what he was trying to do there

spring creek
graceful snow
#

Hello everyone, can someone tell me why the Character Controller lifts on the yAxis 0.22 after pressing W and trying to move?

leaden ice
#

turn on gizmos so you can actually see the CC

graceful snow
leaden ice
#

looks fine

#

Do note that CC has the "skin width"

#

which is extra space beyond the collider shape. You have it set to about 8 centimeters

graceful snow
hybrid turtle
#

Hi Ive made a scene transition like a simple cross fade but as the next scene loads in it shows the skybox scene for an instance of a second

#

idk why it could be doing that is it mistiming the animation?

#
        {
            transitionAni.SetTrigger("Start");
            timerCount = timerDuration; // set back to the duration
            yield return new WaitForSeconds(transitionTime);
            SceneManager.LoadScene(sceneIndex);  
        }```
#

like my loadScene is super simple

#

the animation I made is 1 second which I pass in as transition time

dusky lake
#

Does your animation fade to black and back in 1s or just fade to black?

#

Cause best would be to fade to black -> load new scene -> fade back to normal

#

also how are you fading to black? a black image overlay?

hybrid turtle
#

fade to black and back in 1seconds

#

ill show screenshots

#

i based it off the Brackey's tutorial

#

I have a sceneLoader prefab

#

then a panel that holds a raw image which is coloured black

dusky lake
#

Well best would be to make 2 animations,

  • Fade to black (Animation 1)
  • Load scene
  • Fade back to normal (Animation 2)
hybrid turtle
#

wait yes i have those two

#

I have one that fades in

#

and anothe that fades out

dusky lake
#

How do you trigger the fade-to-normal?

hybrid turtle
#

I made a trigegr called Start in the animator then just in my loadScene

#
        {
            transitionAni.SetTrigger("Start");
            timerCount = timerDuration; // set back to the duration
            yield return new WaitForSeconds(transitionTime);
            SceneManager.LoadScene(sceneIndex);  
        }```
#

call SetTrigger on it

dusky lake
#

Yes but thats the fade-to-black

#

how do you trigger the other one?

hybrid turtle
#

I believe its in the animator sorry its my first time doing these

main coral
#

Why u dont fade with a Canvas ?

dusky lake
#

So your animator instantly starts the fade-to-normal again?

hybrid turtle
#

yes

dusky lake
#

I would wait until the scene is loaded

#

Add another trigger, thats set after the SceneManager.LoadScene()

hybrid turtle
#

ok should I use LoadSceneAsync() and wait for the asyncOP

#

or just LoadScene() fine

dusky lake
#

No it doesnt matter, if your game is black and nothing is happening

hybrid turtle
#

ok ill add another trigger to it then thank you

dusky lake
#

LoadSceneAsync is helpful if you want to load it in the background while stuff is happening

hybrid turtle
#

yes Ive been trying to experiment with it to load in scenes fatser

dusky lake
#

So just to be sure, you saw the skybox of the old scene for a brief moment?

hybrid turtle
#

yes

#

just here i can show it

dusky lake
#

Ok, yeah then waiting for the load to finish until you fade back will most likely fix it πŸ˜„

#

if thats not enough you can add like a 0.1s delay until you start to fade back

#

which is a bit hacky though πŸ˜„

hybrid turtle
#

yeah seems a bit hacky so would you still add the trigger to the default transition state

#

and then set it off after the LoadScene()

dusky lake
#

Yeah

hybrid turtle
#

ive been trying to do that but it wont let me edit the default transition

#

like when I click on it inspector doesnt show an option to add a trigger

dusky lake
#

can you show a screenshot?

hybrid turtle
#

yeah ofc

#

thanks for the help again

#

whereas the other shows this

dusky lake
#

Oh i get it now, add an empty first state that does nothing

#

the entry -> x is not a transition, rather just symbolism for "stuff starts here"

hybrid turtle
#

ok

#

bruh thats confusing

#

like this

dusky lake
dusky lake
spring creek
hybrid turtle
dusky lake
# hybrid turtle

Perfect, now you can edit the transition between intro and the fade-in

hybrid turtle
#

yes I added a trigger to it

#

introStart

#

then updated this

#
        {
            transitionAni.SetTrigger("Start");
            timerCount = timerDuration; // set back to the duration
            yield return new WaitForSeconds(transitionTime);
            SceneManager.LoadScene(sceneIndex); 
            transitionAni.SetTrigger("IntroTrigger");    
        }
dusky lake
#

transitionAni still references the fader in your old scene though, right?

hybrid turtle
#

yes

#

i believe it should

#

transitionAni is the animation controller

slate trellis
#

I have an attack bullet homing on a target using RigidBodies. My code works but it poses a bug that, the closer it reaches the enemy, the slower it moves. I know it is due to multiplying the values but that's how everyone said to do it. I do not want to use MoveToward because it feels clingy and stuttery. here is the important code:

float speed = 2000f;
// enemy is assigned in another script

rb.velocity = speed * Time.deltaTime * (enemy.transform.position - transform.position);
dusky lake
#

Well you can somehow get the reference to the new scene but what I would do in your position:
Have only one fader for your project, dont add one into every scene

  • Create your fader object and use DontDestroyOnLoad() on it (prevents it from being discarded on scene load)
  • Call this fader whenever you want to load a new scene, you can just transition back and forth between the two fade-in and fade-out
wide dock
#

(enemy.transform.position - transform.position).normalized

hybrid turtle
wide dock
#

also take out deltaTime

leaden ice
#
  1. You're not normalizing the direction vector
  2. You're using deltaTime when you shouldn't
wide dock
#

velocity is velocity

slate trellis
#

omg I forgot. I used to actually have the .normalized but I ommited it by accident after reorganizing the code to be easier to read

wide dock
#

When a car goes 60km/h it's just 60km/h, not 60km/h times 0.01 second

#

Then it becomes distance, not velocity

slate trellis
#

ah.

#

I am not in the best of minds today. these mistakes should have been easy to spot. I feel embarrassed

#

thanks for the help

main coral
#

Hello, I use a FreeLook Camera where I have to assign Follow and Look At variables in the Inspector. I'm currently converting my game to multiplayer, what's the best way to ensure every player has their own camera?

#

Because I can't assign the variables because the "Player" is spawned as a prefab.

leaden ice
#

You can make a simple script to "eject" the FreeLook from being a child of the prefab when it spawns

hybrid turtle
#

cuz it was being destoryed on load the canvas holding the transition would be loaded again each time

#

that would be the skybox scene shown

main coral
#

@leaden ice thanks working fine

#

Do I have to eject it as child when it spawns ?

#

I have the problem when I have the camera as a child of a player when another player spawns the camera is changing to the new player

cobalt dune
#

Hello everyone! πŸ‘‹

#

How can i serialize observable collection, to add items via inspector?

#

Or should i create my own class?

latent latch
leaden ice
#

you could have the same script that does the ejecting also just destroy the cams for non-local players

main coral
#

But every player need a camera

#

sorry I dont understand that

leaden ice
#

As a single player, you don't need a camera object in your local game simulation for some other character's player object.

#

you only need your own

main coral
#

Is there a tutorial of that ?

leaden ice
#

what do you need a tutorial for?

#

Your network framework has a way to tell if you own a particular object, yes?

main coral
#

What do I have to do ?

leaden ice
#

if (!IsMine) Destroy(theCamera); pseudocode

#

very simple

main coral
#

Where I have to add this ?

#

IO only have the camera now as child