#archived-code-general
1 messages Β· Page 216 of 1
Input.GetKeyDown and Input.GetKeyUp() based on the scene
this is right/
if (gameObject.CompareTag("Red") || collision.collider.CompareTag("Red"))
{
Destroy(collision.gameObject);
Debug.Log("Worked");
man doesnt work how do i fix it
where is the hint? @box
i linked you directly to the message. #archived-code-general message
stay in one channel btw. keep the conversation in #π»βcode-beginner where it belongs
Hello how can i calculate the stopping point of a rigid body when an impulse force is applied to it
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);
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
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
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()
Vector3 forward = Vector3.ProjectOnPlane(Camera.main.transform.forward, Vector3.up);
activeUser.transform.rotation = Quaternion.LookRotation(forward);```
Something like this^
Code version of what I said yes
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
tis only two lines of code π
cool it worked, thanks
@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
if (Input.GetKey(YourKeyHere))
{
timer -= Time.deltaTime;
}
if (timer <= 0)
{
// timer expired. do stuff
}
In Update. Avoid pinging specific users
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
No, not really
Have a second float. When it is a whole number, reduce it by one and add one to the timer. But why would you ever need that?
If you need to display seconds then you can format it to get rid of the decimals
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
ok maybe im just having a brain fart
The code is assumed to be in Update which runs each frame
yeah ofc then I guess it would have to be 30 seconds then
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
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?
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.
I think you are looking for
arccos(A x B)
where A is your forward direction, B is your direction from vec1 to vec2, x is dot product
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?
from what i see, OverlapCircle has overloads that allow u to take the collection of results
https://docs.unity3d.com/ScriptReference/Physics2D.OverlapCircle.html
They might just be combining it into 1 function instead of having a non alloc version
Hmmm. I've not had much success trying to pass in an array for it to use.
show what you've tried
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.
use the one that has a array of collider2d for a result arg
it wants a contact filter, since u are using a layermask it thinks u are using the other method
pre allocate that array
Hmm. I see how do I change a layer mask into a contact filter?
just construct one
its a struct you can just make a new one that set up what you care about on it
Ahh ok. Hadn't touched that object type before. Thank you let me give it a shot.
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
Yes I anticipate reusing the same List so as to never garbage collect.
with a list it still might GC or do a copy
but only when list expands past its capacity
: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.
Well for 50,000 NPCs that spread it out over the course of 1 second.
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
Yeah I'm spacing it out over time.
either way yeah pre allocated arrays or lists and reuse them
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.
@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
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.
Also, Out of just general curiosity, You mentioned your game is top down 2d. Do you need to be applying gravity?
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.
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
Every Unity tutorial or game design course I've observed has called out never to use SetPosition, always use MovePosition.
And MovePosition involves physics.
moveposition still breaks the physics engine. It just allows interpolation to still work correctly
Again, I could be totally wrong due to lack of information on your specific game but worth considering if you even need friction in this context. you can still apply force without gravity being enabled
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
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
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.
rigidbody material type?
yes so my NPCs have a Ridigbody2D component, and in that is a Body Type.
I don't know what you're doing, but if you want physics enabled AI, then you'll need a steering behavior
setting a rigidbody's position/orientation manually will not give you what you want.
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.
sounds like more complication then is needed is being added somewhere
you can keep your rigidbody on dynamic, but I think you can disable gravity and ignore having to check for ground collisions if your npc height is consistent
like have done my own A* and Steering, and if i want pathfinding never had to bring applying physics forces into it
How many NPCs do you typically support?
I like the A* Pathfinding Project because it uses ECS and is multithreaded.
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
@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
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.
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?
manually depenetrating them would probably be a lot easier on the CPU
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
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.
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.
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.
ensure that you're only calling this on a fixed tick update, not a frame update
It is kind of impressive how a modern Android/iPad is 50,000x faster than one just a couple years old heh.
its not that much faster
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.
the cost of a light varies greatly
At the moment I have settings to enable/disable the lights, the shadows and swap all the materials with non bump mapped versions.
depends on if you are in deferred or forward
in forward the cost of the light is re-rendering anything it hits
By default I believe URP is forward?
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
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?
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
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.
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
Thanks!
Oh nice, thanks!
Very cool, thanks. That version is very new and it says it's still in Beta. Probably why I missed it. I'll definitely look into this more.
Yeah he's been porting over Beta features on a regular basis. So far so good.
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?
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?
You could always make another scriptable object that holds your items in a list. You could even make it scan your assets and add them to the list automatically.
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;
}
When checking the profiler if itβs not directly naming a method or file how do I know what the spike is referring to
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>>
you don't know, you need to analyze it, add profiler markers, or do deep profiling
What is profiler marker and can frame debugger help me in anyway
frame debugger is for GPU stuff
Thanks!
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?
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
Oh cool, thanks for the insight(:
I'll investigate further with that in mind
Similar to signal change
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?
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
Unity has a LOD Group component built in. You can set a distance where it culls the renderer completely
Yeah its only visual, you need something else then
rendering isn't terribly hard on 2d
Missed the 2d part
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?
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.
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;
}
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
thanks π
Hey guys, why can I use NativeArray from Unity.Collections but NativeHashSet (https://docs.unity3d.com/Packages/com.unity.collections@2.3/api/Unity.Collections.NativeHashSet-1.html) does not exist?
do you have that package installed?
NativeArray is part of core Unity, under the same namespace. Additional collection types are found in the package.
Thank you guys, you're right! Including Unity.Collections from the package as an Assembly Definition Reference did the job :)
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 π₯³
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.
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.
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
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
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
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
Yeah I have a similar system in one of my games
Bridging the gap between code and data can be very fiddly
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
right, everything has OnChange events (or could trivially have them added)
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
I assume you can do things like VitalStat healthStat = character.GetVital(VitalType.Health);
π«
Right. You actually get a VitalStatValue, which is where the mutable data lives, but same concept
Delicious serializable data
I will think about this some more. Iβve got lots of less complex stuff I can focus on for now
How do you check for calculations like double damage and such? Like lots of miscellaneous status effects can bunch up pretty quickly which is the bigger problem, so I'd assume you'd want to group those all out.
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);
}
}
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?
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
I feel that is pretty simple isnt ?
public interface Modifiable
{
public void AddModifier(...);
public void RemoveModifier(...);
public Modifier GetAllModifier();
}
You could even do a MonoBehavior to implement the interface and reuse it everywhere.
So, to catagorize them. Trigger on hit, trigger when hit, trigger over time, trigger when moving, ect.
Different modifiable things would have very differently shaped modifiers. Some would be a simple float, some would need to rewrite entire damage instances, ...
Yeah, that would be some C# black magic works. Nothing impossible to do.
But I'm not concerned about the interface, really. I'm just thinking about how I will attach an effect part to an entity (and later remove it). The last three code blocks in the original question show what that might look like
I actually tried something similar to that. The only problem with this system is recalculating the hundreds of stats. So, ideally I'd cache it all as soon as a status is changed.
Cant you just use that ?
private List<Modifier> modifiers;
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.
there are many different kinds of modifiers that are relevant in many different places
This is possible with what I have shown. You simply need to add some event
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!)
It wouldnt be. You could have by example something like:
public class StatusEffectPartFloat : StatusEffectPart
{
[SerializeField] private float _value;
public float GetValue()
{
return _value;
}
}
You could even use generic
Ah, so defining one part for each kind of data
Not for each thing that can be modified
Exactly, you would need to cast it to the appropriate type when used though
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.
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.
As I said, you can definitely cache the GetModifier return. You could even cache the result of the operation that requires multiple modifier.
//Refresh when needed to be
float cache = (base + flatModifier) * percentageModifier;
...
float result = damage / cache;
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.```
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?
Ask this in #βοΈβeditor-extensions
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!
whats the use case?
using tags is kinda slow well not really but depends how many times
I don't really have to use tags, it can be any way to get certain gameobjects into a list
FindObjectsOfType also works, doesn't explain why it can't be done prior with serializing in inspector
explaining the use case would help
I can't use the inspector bc those gameobjects (cars that will be driving all around the map) only spawn on hit play so that it generates random cars in random positions
so add it to the list when you spawn them
Instantiate returns the instance of the object
oh right! I dont know hoe I didn't think of that earlier, thank you very much!
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?
FixedJoint?
Or attach the hingejoint to the player rigidbody, not sure what you mean
Or is the hinge between the handle and the lantern?
the hinge is between the handle and lantern
would i be able to than connect the lantern to the player with a fixed joint?
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
im gonna try to make it with the fixed joint. But would the fixed joint be on the player or handle?
I think that's up to you
ok im gonna try it out thanks!
See if it behaves differently, it might not matter
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
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
the sprite itself has https://docs.unity3d.com/ScriptReference/Sprite-pixelsPerUnit.html
it's uniform on x/y though, not different on each
Could someone tell me why foreach doesnt run here? https://pastecode.io/s/r058wnic
inside the json file https://pastecode.io/s/jqq6vgmr
your object hierarchy doesn't match the JSON
just finished implementing my lantern with the fixed joint and it worked great thanks a bunch!
did you debug it?
the json that would match that class would look like:
{
"translations" : {
"moodle_hunger_level_1": "Hungry",
"moodle_hunger_level_2": "Very Hungry"
}
}```
... yeah that was it, thank you. Still learning how to work with json
thx!
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
make smaller scenes. the "delay" is it instantiating all of your objects.
but yes, there is a LoadSceneAsync method
well, then it's going to hitch
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?
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
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
Why not just unload the scene you don't want?
Anything you want still loaded should be in its own scene
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)
oh god singletons
I need to start testing more elaborate scenes
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
in the new input system, yes there is cursor warping support
not in the old system
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;```
The constraints property is a combination of various choices
it's one of those enum flag situations
if you are freezing rotation you will need a little more complexity
A | B | C
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
tell me one thing. I know it may be obvious but, can I mix two input systems?
The getkey isn't working. Here's the code; https://pastecode.io/s/1dwoum1a
new and old
yep
just set active handling to Both
So I suppose you could just use the new input system exclusively to move the mouse cursor
highly recommend just learning the new system though, it's pretty good
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
Wdym by "isn't working"? What are you expecting it to do?
It seems to be ste up to do nothing right now:
if (Input.GetKey(KeyCode.Z));
Yeah this piece of code is very wrong
in fact all of your if statements are doing nothing
that semicolon means "end the statement here"
your code editor should be giving you warnings every time you put a semicolon after an if statement
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"
Plus it's in Start, so it'll only happen once
Didn't even see that lol
an if statement will run the statement that follows it if the condition is met
; terminates a statement
and empty statements are legal
I was too distracted by the semicolons
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.
I tried removing the semicolons, but nothing happened.
You'll have to do way more than removing the semicolons, really - seems like you need to learn C#
what do you expect to happen?
Did you read the rest of what was said here??
!learn
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
I wanted the circle to move up and to the right when z is pressed.
scroll up and read all the messages from about here: #archived-code-general message
Here's an important one too: #archived-code-general message
It didn't work.
I tried removing the semicolon, but nothing.
well, of course not, because all of this code is still in Start
It's still not doing anything.
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
Is line 20 meant to be execute only when the conditions in the if statements are satisfied?
Because that's not the case here
How do I fix it?
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

It worked! π
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?
You can load the scene additively. Or, don't use a separate scene at all, and enable/disable the needed objects
Oh, you are correct! But I have already made the scene. I can use like it says SceneManager.LoadScene(Scene name, mode LoadSceneMode.Addictive) right?
Yep
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
hey guys I have an unassigned ref going while I switch scenes thats an animator
even though it is assigned in the other scene
@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.
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
Yup, that's exactly what additive loading does. It adds everything on top of your already opened scenes
You'll need to disable the objects you don't need to see
Oh, ok.
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
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!");
}
}```
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
Ok!
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
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?
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.
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.
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 '-'
Is it in a Resources folder?
Is it referenced from any script or object in the scene (even transitively, e.g. through a prefab)?
No it's in Assets folder, and no, it's not referenced, I created an empty project with just a mesh D:
try profiling a build
the editor may have things loaded in for all kinds of reasons, like creating asset previews etc
Interesting, might do something similar, also considering using some item name or id, and just getting it from a list by id
technically you could consider unique names as IDs
hm I just so happen to be working on something similar, would the hashcode of a scriptable object be reliable as an ID?
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.
is that the GetInstanceID()?
not sure what assetID is
string assetPath = AssetDatabase.GetAssetPath(this);
storable_ID = AssetDatabase.AssetPathToGUID(assetPath);```
oh thats editor only right? hm i might just stick with hashcode until i notice a problem. then ill try that
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
this is just for premade items so wont create at runtime
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...
yea just foreach over the queue
ty. just wanted to make sure it would work like that
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
Because you are calling SetActive(false) in Update
Update runs every frame
should i remove it?
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
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?
I set a variable to 0 and change it, but it goes back to 0. Here's the code: https://pastecode.io/s/3rhww3mm
Sounds like the first statement is not true.
Easily verified with Debug.Log
It's because your ifs are being executed one after another. If you want only 1 if to be executed at once, you can use else if for ifs after the first one. Alternatively, you can use a switch.
The whole implementation here makes no sense. Don't you want this to happen over time?
As twisted bush said, it happens all in one frame. Doing else if or switch would make it happen in 4 frames
So either way I assume this is way faster than you want
Late reply, but it worked.
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
There is no yield in your coroutine
You must yield the main thread inside the while loop of CheckPlayerVisibility
while(true) is literally an infinite loop. And the makn loop can never return from that loop
question: when does the content of a coroutine up to its first yield evaluate?
is it on the same line that it is started?
you're right, i forgot to yield, i completely oversaw that. thanks\
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.
What C# version where they introduced in?
trying to look it up
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 ?
it's seemingly C# 3.0 π€
Yeah. You'd think they're supported. Maybe it's something else?
well I only changed
.Select(p => (p, Score(p))
to
.Select(p => new Scored (p, Score(p))
and it stopped crashing
Isn't that a tuple in the first case? Pretty sure tuples are supported though.
How do you use the value?
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...
I would look into bezier curves, there is a ton of implementations... you can even make your own, it's not that complicated. Drop me a dm if you need to
You do t need a curve for that. You can calculate the boomerang displacement to the side with lerp.
t = distance from player / distance to the target;
t = t*2. - 1;
//Now t would be 0 at both ends and 1 in the middle. Multiply the max displacement by it to get the displaced distance.
What I mean is what happens to the tuple afterwards
Maybe share the whole line of code.
Usually games like Zelda have the boomerang homing back to the player and not the position it was thrown. I'd look into methods like RotateTowards for that behavior.
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
thanks for your answers! I'll look into that (and ask more questions π) tomorrow
What dot net version are you compiling against btw?
.NET 6.0
Ah, that might be the problem?
Doesn't it need to be a version that unity supports?
well... it started working just when I changed the anonymous class though π€
It could be that the dotnet 6 treats the tuples in the old code differently
what version is that? I consulted the dll import page (https://docs.unity3d.com/Manual/UsingDLL.html) and there is not a word about it
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
I guess this is sort of relevant:
Setting up the Project
Open Visual Studio and create a new project.
Select File > New > Project > Visual C# >** .Net Standard** > Class Library (.NET Standard).
oh gotcha π€ I will try using .NET standard and see
Does it not?π€
No because Update is a Mono event
On that, is "[ExecuteInEditMode]" redundant when you inherit from Editor?
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
Why can you not put a MonoBehaviour on the prefab?
It says it can't add script behaviour because it is an editor script
Is it in the editor assembly?
Not sure what you mean by "Editor assembly"
In an editor folder
Yeh yeh, I think that was the issue actually
Then it is in the editor assembly
It wouldn't let me use "AddComponent" from a script that is in the Editor folder
And editor assembly is not available at runtime.
Then take it out of the editor folder.
But I don't need this at runtime π¦ it's for the Prefab editing scene
You don't need the Whole script or just the part that does the editor logic?
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 π
If it's purely for editing time, might want to hook to some editor event instead, since Update is not available.
I would much rather go that route rather than relying on a monobehaviour yeh
Ideally, yes.
I have a custom PrefabEditor window... I could call Update on the ChangeTracker from the OnGui in there? 
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.
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
Perhaps.
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 π
okey works on standard. nice, ty!
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.
transform.translate doesnt respect collisions at all
yeah that collision code is really strange
and most likely the source of the jittering
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
Yeah. I try to overly soften what I say sometimes, to the point of just being wrong π€¦ββοΈ
depending on how that base.TimeManager.TickDelta is calculated, you could probably teleport through walls with that code by lagging intentionally
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
I figured it out. It's this
Need to flip to project and use other UIDocuments
I'm glad to find that out. Thanks. I wondered the same before
In the future though, try this channel
https://discord.com/channels/489222168727519232/892762498464374796
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
Thanks! didnt know it was there
Managed to get it working
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
Easy to replicate
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?
Share the error details@rancid pond
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.
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)
KingTrigger funtion should be invoked with parameter "collider other" from event trigger right?
No
It's registered in the inspector, so it would use the parameter from the inspector
ok got it.. thanks
ok so i know how to fix it but why is this not allowed?
nevermind that didnt fix it lol
What do you mean not allowed?
i figured it out its because i didnt specify that the barrack type is public
you have to set up your editor
also fuck yeah gojira
i might not have
im kinda rusty on unity lol ive been doing only c++ and gamemaker things for the past few years
did it noww
Hey guys im looking for some opinions on my current code
a powerful website for storing and sharing text and code snippets. completely free and open source.
Is there a reason NightManager is a scriptable object? its generally not recommended to use SO for mutable (changing) data.
You should also null check those c# events to make sure it isnt trying to invoke while nothing is subscribe
I dont see how u are running public IEnumerator RunGame() either, since you need a mono to run coroutines
someone else suggested to do that because of how easy it is to change and edit the values
Currently RunGame isnt being run anyway as i havent got to making the actual nights yet
you should try running it once before you run with this solution
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
you cant run a coroutine on a scriptable object, so you're gonna have some weird dependency in this structure. You can run it on another monobehaviour like GameManager but this is just awkward imo. It really feels like you're using a scriptable object here when you shouldnt
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
you should be testing methods by running them right away to make sure they work. if you cant test a method yet, then you might wanna work on something else or just setup a mini environment so you can run it. I see no reason why you cant just (attempt to)* start the coroutine in this case as a test
i cant run it because it wont be doing anything untill i have some form of ui displaying information and also i have just woke up so u need to explain things a bit more
and i am still learning how UIToolkit works as its a bit weird rn
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
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; β
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
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
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
Trust me what i have now is less than minimum
You cant have a fnaf game without basic things like the power system and Time
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?
its meant to handle Starting the night, ending the night and handling any disruptions such as dying due to no power, or a character getting into your office (havent even started with the other character AI yet as thats a load more work)
Yea suddenly this is more than what it should really handle then
Rungame starts the timer for the night and also Starts the power drain and will eventually enable AIs.
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
Honestly for a game like this it could all go into a single gamemanager
someone else had a massive go at me for suggesting that
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
Character with trigger doesnt work with how the AI works as the character movement is not animated its posed
You know the scope of the game so it's a lot easier to know what your going to have in it
im heavily mimicking how the original games worked
What do you mean by it's posed?
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
}
also I might have missed bawsi suggesting it but for field variables (like HasPower, Power etc.) you want lowercaseUppercase
i have no clue what any of that means, i can just guarantee you right now that you can throw a kinematic rigidbody on it, put a capsule collider, and itll work
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
nothing about that stops you from using trigger colliders if you wanted to do so
its hard to understand if u never played the originals and know what im trying to do
I know the game
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
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
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?
Still, you should experiment with physics messages (namely OnTriggerEnter) because itll be a lot easier to have spaces that detect when an enemy is inside it, then do stuff like end the game.
Anyways I gotta go
well it will be more like start a random timer before u get killed
You can just recalculate the navmesh after generating, doesn't that fix your problem?
how can i bake the navmesh during runtime?
https://www.youtube.com/watch?v=mV-Uh_FEBn4
I have never done it, but you can do it. But googling probably gives you a better answer.
thank you!
Am i meant to keep the RunGame in the NightSettings or move it to the GameManager
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?
You can look at the IL or assembly I guess.
But I really doubt you'll see much difference wether it's in lined or not.
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}");
}
}
Confused because that looks like a world space canvas in the image but you're showing a screen space canvas
I'm rendering the UI to a rendertexture, and the tablet has a material with the diffuse texture set to the render texture
It's for a VR game, so I want a custom interaction system where you tap the tablet
Why not just use a world space canvas
This way I can write a shader that uses the texture and renders other elements and effects on top of it
Alright well it's a bit unclear where ptr.position comes from as well as raycaster
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
What's the resolution of the render texture
Oh nvm you said it
yeah lol npnp
I'll probably wind up scaling it down to at least 720p for vr but im just tryna get the raycasts rn
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?
Generic structs?π€
You could write a custom editor/inspector/property drawer if that's more convenient for you.
A struct that takes in a generic, or wahtever one says.
Wdym by "takes in a generic"?
Like
[System.Serializable]
public struct Matrix_Row<Element>
{
[SerializeField]
public Element[] Elements;
[HideInInspector]
public int Length
{
get { return Elements.Length; }
private set {; }
}
}
Ah, yeah. That's a generic struct.
Alr
I looked at some documentation for "ISerializationCallback", though don't know if it'd work in my case.
I'm not sure if that's gonna help with the inspector.
What would this imply?
Writing an editor script to draw the inspector.π€·ββοΈ
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?
Because you would define how to draw it.
You'd draw corresponding property fields(ui) for the struct fields
Is Element marked as Serializable?
Wym?
Ah nvm, the issue is that it's not a concrete type, right
Element is the generic type
I know
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 {; }
}
}
You wont be able to serialized a generic type without specifying it. (Inherit from it and remove the generic)
IGridTile is an interface.
Honestly, I'm not sure there's a point in generics here.
I think List<T> is the only generic that unity can serialize, and thats a special case
Yeah, problem is, I'd have to switch to classes, and would both Matrix_Map and Matrix_Row have to have inheriting classes?
No?
Why can't I write "Hm" π
Matrix_Map and row don't need to change. You'd just use a base class instead of an undefined type.
I'm sure tiles have something in common for them to make sense to inherit from a base class.
Not sure I completely follow. Could you give an example?
No idea, at the end, you cannot have a generic data type if you want it to be serialized. Meaning, you would have to, by example, define:
Matrix_RowFloat
Matrix_RowFloat
Declaring the concrete class is just one linecs public struct Matrix_RowFloat : Matrix_Row<float> {}
But wait this is a struct
Can't inherit
[System.Serializable]
public struct Matrix_Row
{
[SerializeField]
public BaseTile[] tiles;
[HideInInspector]
public int Length
{
get { return tiles.Length; }
private set {; }
}
}
Yeah, but what's BaseTile?
A base tile
Because my use of generic type, is that not only will I have "IGridTile", but also "IGridEntity".
That you can inherit from to implement specific functionality
Sure, you can do the same with inheritance.
So would I have to create an underlying, say "IGridElement" interface?
Oh, but they would have to be classes I guess.
No..?
Thats what im saying
Do you really need them to be struct ?
Why not use classes anyway?
What is the scope we are talking
No, but it's practical
Not really, as you are seeing.
In what way is it practical?
It is usually for performance you use struct
Well it would be practical if this weren't any issue.
In what way?
It shouldn't have to be a class
You need a class if you want generics + serialization here
Because structs can't inherit so you can't make the concrete class
Otherwise, you could always try to comeup with an other serialization method.
And give up Unity serialization
But applying this, wold it have to be done to "Matrix_Row" and "Matrix_Map"?
Like, use a .txt file
Seems even less practical
I mean, the system Unity has made has some limitation, you either live with or you dont use it.
There is not a lot option here.
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?"
Yes something like
public class Matrix_RowMyType : Matrix_Row<MyType> {}
public class Matrix_MapMyType : Matrix_Map<MyType> {} ```
That would require class
It is a class
They wants to use a struc
We still didn't hear the explanation of what exactly is practical about the structs vs classes?π
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
Wait you are right. π€¦ββοΈ And I do it all the time
@amber berry It works fine for me
It needs to be a serializable type though?
Thats a list of generici items, but thats not what this is about
Ah! I think I know now. I am trying to serialize an interface, which I do not believe is possible.
Yep...
Is Element an interface?
well, you can do it with SerializeReference, but it's a pain in the butt
public Matrix_Row<Element>[] Matrix;
Is close to a list of generic isnt ?
Yeah, or the the type used for Element
@amber berry Yeah, thats why i asked my initial question here π
If you named it with the C# conventions (IElement) I wouldve seen that its an interface
Ah, didnβt really understand what you meant.
Yeah, but Element is no interface, itβs the name of the generic type.
The type that is Element in our case is an interface
What matters is what type does the object you want to serialize have.
Not the declaration.
Yeah, drawing it in the inspector will be extra work
SerializeReference is a game changer tho
You're right - that might not work π€
you'd have to make a wrapper struct for the array element type
is there a method that combines the properties of TryGetComponent<T>() and GetComponentInParent<T>()? For example TryGetComponentInParent<T>()?
not built in but it's very easy to write
if((component=GetXXXX)==null){}
For example:
bool TryGetComponentInParent<T>(out T result) where T : Component {
result = GetComponentInParent<T>();
return !System.Object.ReferenceEquals(result, null);
}```
I have no idea what half of those mean
ok?
but still thanks for the notice
you did ask
ik. Thanks. I will experiment a bit and try it out
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?
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
}
}```
forgot to mention
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 { }
2 errors:
- cannot inherit Monobehavior (to use GetComponentInParent<T>()) as it isn't a statc class
- 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
yo don't need to inherit anything
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);
}
}```
ah
makes a lot more sense now
thanks. I will do more research for extension methods and static fields
there are no static fields here
I don't know the terms T-T. In general to whatever static refers to
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.
I also recommend learning the terms since they're quite important for communicating!
this will prove useful. I will save it somewhere as a TXT
Field refers to a class member variable btw.
The reason Praetor said they weren't static fields was because they're static functions.
I learn them in m native language but keep forgetting to translate '
I would recommend preferring English sources whenever possible
I learn at school OOP (Java) and I implement what I know in Unity
static in Java means the same as in C#
why if i call Finalize() on my custom class object, (didnt make the method yet) the VSC shows me the method exists and links to this?
https://i.imgur.com/xR02klP.png
i wonder what it does
ohh thats some destructor
the deconstructor?
because that method name exists already on System.Object https://learn.microsoft.com/en-us/dotnet/api/system.object.finalize?view=net-7.0
Hey, is it possible to save List<byte[]> using JsonUtility.ToJson? Cuz im having some problems with it
no
JsonUtility doesn't support nested lists/arrays
because it uses Unity's serializer which doesn't support nested lists/arrays
i see
so how can i convert it to json then?
what would be the easiest work around
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;```
or use json.NET
alright, thanks!
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;
}
!code
π Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
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
You have to pass in an array of strings.
You're passing in two separate single strings as unique parameters.
ok how do i do it
you need params in this case
Make an array of strings π€·ββοΈ
i asked how to do it
i will just look it up
You either hardcode it, or you expose it to the inspector via [SerializeField] string[] myArray and type it out there.
either add the params keyword or give it an actual array of strings instead of a regular string
i fix it
hey what's with this:
Instantiating mesh due to calling MeshFilter.mesh during edit mode. This will leak meshes. Please use MeshFilter.sharedMesh instead.
string[] myArray = new string[] {"Plant", "PlantRoot"};
looks slightly better
oh you can do that!
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
you could just do this
string[] layersTarget = new string[2]
{
"Plant", "PlantRoot"
};
can't it GC the temporary mesh when it's not being referenced anymore in the scene?
yah Gruhlum just told me there
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.
donβt cross post
OK sorry!
you posted your query in code general, beginner, and advanced. pick one and delete the others
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..
@lament raft
You could also use params
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/method-parameters#params-modifier
UnityEngine objects cannot be GCed because C++ doesn't have a garbage collector
you have to use Destroy to destroy Unity objects
anyway the error tells you exactly how to fix it
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().
yep
OK guys, I found the error.
You should go through the documentation from top to bottom and not start in the middle.
xD
i dont think params would be the best fit for that
It'd let you use it by passing in separate strings as parameters which is what they seem to be trying to do
i know, but i dont think he did that on purpose
Params would be exactly what they need here
to write it like that yes, but i dont think he wanted to write them like that
You are right, but how he wanted to write it is irrelevant. Why have the array middleman instead of params. Params is the absolute best fit for what they want imo
Much more flexible and simpler syntax
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
Pass a variable number of strings via a method
Hello everyone, can someone tell me why the Character Controller lifts on the yAxis 0.22 after pressing W and trying to move?
presumably it's colliding with the ground
turn on gizmos so you can actually see the CC
Thank you, i did not think about the ground asset, now i see the Mesh collider is lifted a bit, i made this SS where you can see better what i mean.
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
Yeah, i noticed. Thanks, you helped me a lot.
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
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?
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
Well best would be to make 2 animations,
- Fade to black (Animation 1)
- Load scene
- Fade back to normal (Animation 2)
How do you trigger the fade-to-normal?
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
I believe its in the animator sorry its my first time doing these
Why u dont fade with a Canvas ?
So your animator instantly starts the fade-to-normal again?
yes
I would wait until the scene is loaded
Add another trigger, thats set after the SceneManager.LoadScene()
ok should I use LoadSceneAsync() and wait for the asyncOP
or just LoadScene() fine
No it doesnt matter, if your game is black and nothing is happening
ok ill add another trigger to it then thank you
LoadSceneAsync is helpful if you want to load it in the background while stuff is happening
yes Ive been trying to experiment with it to load in scenes fatser
So just to be sure, you saw the skybox of the old scene for a brief moment?
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 π
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()
Yeah
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
can you show a screenshot?
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"
Look for "Light bleeding [under walls]", lots of solutions
Add it between entry and AnimationEnd
Not a code question
Try #archived-lighting
Perfect, now you can edit the transition between intro and the fade-in
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");
}
transitionAni still references the fader in your old scene though, right?
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);
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
just normalize the direction vector
(enemy.transform.position - transform.position).normalized
ok ill give it a shot thank you again @dusky lake
You have two problems here
also take out deltaTime
- You're not normalizing the direction vector
- You're using deltaTime when you shouldn't
velocity is velocity
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
When a car goes 60km/h it's just 60km/h, not 60km/h times 0.01 second
Then it becomes distance, not velocity
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
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.
Best practice IMO is to include the FreeLook inside the player prefab
You can make a simple script to "eject" the FreeLook from being a child of the prefab when it spawns
ok I see what the issue was
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
@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
Hello everyone! π
How can i serialize observable collection, to add items via inspector?
Or should i create my own class?
You should not have those camera enabled for every player then and disable them via client
yeah only the "local" player's cam should be enabled
you could have the same script that does the ejecting also just destroy the cams for non-local players
only on their own computer do they need cameras
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
Is there a tutorial of that ?
what do you need a tutorial for?
Your network framework has a way to tell if you own a particular object, yes?
What do I have to do ?