#💻┃code-beginner
1 messages · Page 239 of 1
Is it raw data? Or does it contain headers? Do you have a link to documentation?
so if you are interacting with a React Web App why are you not using UnityWebRequest?
I suppose it's raw data in a sense
It is stored in the Vector3
that is the answer suggested by this post https://stackoverflow.com/questions/75124607/how-to-convert-base64-mpeg-to-audioclip-in-unity
which worked great in the editor, but not in the build due to the use of Application.persistentDataPath not working as expected
Think of it as relative to (0,0,0). As a point, it's an offset relative to that position. As a vector, it's an 'arrow' which starts at the origin and ends at that 'point'.
Sorry but if you use UnityWebRequest corretly there is no need to use PersistentData
How can I retrieve it from Vector3 object , via normalized ?
I don't think UnityWebRequest can read base64, only URLs I believe
The purpose of PersistentData (in the SO answer) is to store the converted base64 as a url, which unitywebrequest can read
The vector itself is a direction
It already has the direction implicit in it. If you normalize it, it will be pointing that direction with a magnitude of 1, which is useful if want to scale it by some other amount instead of it being the length it already is.
if you need it normalized then normalize it
There is no reason for the data to be in base64, your web backend can send the data correctly with the right mime type
There is no backend
you said a React Web App, that is the backend
Hmmm time to go back to school algebra . Thank you @keen dew @night mural @teal viper
I said the audio is recorded by the user, so the audio is stored on the user's browser. A React App is not a backend
Firebase would be considered a backend, but I'm not storing anything on there yet
So you have unity WebGL build integrated in a react app, is that correct?
yes
sorry i haven't really been following, what's the request for if there's no backend?
To send a recorded audio clip to the unity WebGL build
you can probably send a POST with the data you want in the right mimetype but if you have no backend i'm not sure that makes sense
requests don't send stuff, they request stuff
You already know how to convert your data to a byte array. From there look up "unity create audioclip from bytes". There were a few promising results on the unity forums.@potent nymph
Yes, I think I looked through all of them
if there's nothing external you shouldn't need to make any requests
There was a result about using AudioClip.Create. look it up.
@night mural that's correct, and that is exactly how I'm passing in things like numbers, strings, and even textures to the WebGL build from the frontend. But for audio it's a bit more tricky
i mean, they can send stuff, but it seems like a weird way to accomplish what it sounds like you're doing (though admittedly i am missing a lot of context)
oh i see, so the react app wraps the unity app and you are making requests to it? then it is sort of a backend but i get the confusion
there are no requests being made, but they do interact with each other

what does that mean
well if you don't want to send it as base64, you can probably POST it with the right content type, but i'm not sure if that solves your problem: https://docs.unity3d.com/ScriptReference/Networking.UnityWebRequest.Post.html
the react app acts as a wrapper so I can use certain web apis (like accessing the web cam, microphone, and using other js libraries)
anyone know why?
every other animation works fine even idle injured works fine
only when the injured walk is played
ive tried replacing it with every animation but every animation does it in the "injured" state
except idle
yeah that's interesting! but i've never done that so i donno how gnarly it is to get those to talk to each other
It seems like there's an animation event in that animation, and you're not handling it.
is there something like MonoBehaviour.OnApplicationQuit() except when the scene changes?
Either remove the animation event, or create a method to receive it.
There are callbacks in SceneManager that you can subscribe to.
just in case you didn't also find this https://forum.unity.com/threads/how-to-convert-base64-mpeg-to-audioclip.1398631/#post-8820691
Yeah, that's a solution similar to what I've found as well.
I haven't tried downloading a package with nuget before
Try the solution in the post first.
yes, the solution requires this library https://github.com/naudio/NAudio
If I have a character and I want to implement stats for said character, would it be better to just spread the stats out around many scripts (so Health would have HP, Movement would have MoveSpeed, etc) or place them all in a single class called Stats?
Where do you see that it requires it? They just mentioned that it could be helpful.
The main thing is AudioClip.Create and .SetData.
Assuming your data is in the correct format, you just need to convert it to a float array.
but as I'm trying out the codes, certain methods don't seem to exist, such as ConvertByteToFloat
I can only assume I'm missing something
That method is defined in the topic starter post.
never mind I see the function from the OP
Either can work. If you'll have a few stats into which many effects are distilled systemically and are unlikely to add more on a whim, it might be simpler to just group them together as a core part of a character. If your stats are going to be more numerous/complex/interesting/broad-reaching, you might want something more component-based and flexible to enable that.
A lot of things in games can be distilled down to 'a tag and a number' but it's often useful to draw boundaries between them anyway. Call your tag+numbers that every character needs Stats and couple them to the character functionality. Call the ones that are more dynamic Auras and apply/remove them dynamically. Whatever helps you keep things organized!
The solution on the post didn't seem to work at first but at least I heard a sound. I'll keep working on it
just a thought, can you not use indexedDB to pass the data between the react app and the unity app?
i think that was the original plan? (webgl uses indexedDB to store persistent data)
I was looking into that, I'm not sure
pretty sure you can save the file in there and then pull it out but i don't know how that works offhand (just that persistentDataPath points there somehow in webgl builds)
I think a lot will depend on how the React app has wrapped the Unity app
I'm using this module: https://react-unity-webgl.dev/docs/api/send-message
The send message function lets you asynchronously invoke a method in the Unity game.
I think the main issue here is what kind of data do you get from the microphone in JS and how to convert it to a format that AudioClip expects.
could I have some pointers for architecting a class/ability system? should I have a BaseAbility which inherits from scriptable object then have for example "ActiveAbility" and "PassiveAbility" inherit "BaseAbility?" or should I not use scriptable objects? same thing for class, I want to have a class system along with subclasses. for example an Archer could become a Marksman or a Trapper later on. Should I have a base "Class" which inherits scriptable object. Then have "Archer" inherit "Class" and then have "Marksman" inherit "Archer." Does this make sense?
Would definitely recommend SO for abilities, as you'd probably have a lot of them, and SOs are easy to config and change in the inspector. As for classes, you might need a combo of SOs for data and plain classes for behaviour. Though, it depends a lot on your project.
I am making an ARPG very similar to diablo 3 or path of exile
Inheritance is an option, but there's also composition and you can combine both too.
I was just worried going down the tree of inheritance since I would be making a new scriptable object for each ability
since I want completely seperate logic
then i would probably avoid inheritance and try to do as much composition as you can
alternatively though, I could have an AbilityLogic class which every ability SO has?
not sure
yep, definitely avoid trying to build a complicated hierarchy here as it will never work
Yeah, still it depends on the project. 2 arpgs can have a totally different architectures
yes just wondering the most effective way of doing it
the answer is always 'it depends'
focus on composition and try avoiding an inheritance chain, especially, for BaseClass > Archer > Trapper, etc . . .
or atleast what to avoid
how would I do that using composition
what do your items look like? what do your abilities look like? where do they come from? what sort of things can modify them and how? in an arpg the answer is often 'everything affects everything' which leans more towards an ECS kind of architecture
If your game is small I see nothing wrong with an inheritance structure. Say the Spire did the same and ended up alright.
Break the classes logic into smaller common objects and logic steps and make them into their own classes.
If you want the ability system to be pretty complex, then ya consider composing them.
yes thats what I planned on doing
each class woudl just store a list of abilities
and have a name
well composition would mean that instead of PassiveAbility and ActiveAbility classes, your ability class would have an ActivationTrigger (or something like that) which would be set to 'always' for passive and 'player_activated_manual' for an active one (not a great example but hopefully you get the idea)
Ya I think it's fine to have some base ability class that holds things like name, cooldown, targeting strategy, cooldown, etc and then a list of "Effect" classes.
Then you can just have one SO with many instances representing the classes
yep okay
i think im too far in to convert everything to ecs, no idea how that even works as well
but yes everything does effect everything
you don't have to actually 'do ecs' to adopt ideas from the architecture
what does that entail then?
behavior as composable data components which are processed by systems at logic time
but where and how you'd implement that would depend on, like, what your game is actually made of
truth . . .
yeah just dont want to go to deep and end up regretting how I did it
not turn based though
oh that will definitely happen
but that's how you learn
true
it's because an 'ability' isn't really anything and often means 'anything that can happen in the game'
Do you need "triggers"? Like "this character has a buff that heals themselves whenever anything takes damage"?
most likely, anythng you would see in the likes of Diablo, POE, etc
or an MMO
those types of abilities
oh yeah, ezpz
its more specific in my case i guess, just skills with cooldowns etc
would using a strategy pattern make sense so the character doesn't have to deal with all the ability logic
what i'm describing here is essentially the strategy pattern
ah okay
compose your abilities out of strategies for the different things an ability must do
so generalize them as much as possible? like im most likely going to have multiple skills that will shoot projectiles in some way
that can just be setup with parameters
e.g. for league of legends, they determined that 'missiles' in their game need to do these things
so each missile can implement a strategy for how it does those things
from this article, donno how practically useful it is because their diagrams are too small 😦 https://technology.riotgames.com/news/behind-leagues-new-missile-system
so avoid writing a seperate script for each abilities logic?
and generalize them to projectile, melee, DOT, etc
if each ability is truly unique and it would be difficult or tedious to distil them down into reusable components, having a script for each might be ok
im not sure yet
thanks for this
but generally if you want your game to be heavily modifiable at runtime like an arpg tends to be, you need things to be data driven
if every ability is an opaque script which just gets Cast()ed and nothing knows what it does, that's ok but it can make it trickier if you have a modifier that needs to reach in and tweak that ability (or that the ability needs to factor into its execution)
The way I would do it is that you have.
- Spells
- Targeting Strategies
- Effects
- Actions
- Triggers
Spells hold data like name, case time, cooldown etc, as well as a list of effects.
Targeting Strategies collect some subset of objects to be used in Effects.
Effects create Actions, and load them with relevant data (DamageEffect for example would create a DamageAction instance).
Actions are the ones that actually change the game state and send events out for Triggers to respond.
Triggers are fancy "event listeners" that will set off new Effects when relevant.
yeah, that's a good setup
effects can be damage, applying an aura, a knockback, etc.
it can get complicated though, as you'll quickly find that you want to do things like 'this ability hits everything in an area, but it should also affect friendly targets, and if the target is friendly it should heal them instead of damage, and if should only hit the 5 closest targets to the center, etc. etc.'
games be complicated though and there's no solution that makes everything simple
Yep you're gonna wanna be pretty robust with your Effects. For example with this, you can have it so your DamageEffect takes in a "Targeting Strategy". This is a separate class whose sole job is to define what entities we're aiming to hit with the effect.
You can have conditional effects that will execute different sub effects depending on conditions etc.
It can get wild, but it's important to identify all these different pieces.
yeah for sure, I do feel like hard coding the abilities would be easier but on the other hand they may all feel slightly different
and would be much harder to add new abilities
Depending on the game scope, ya maybe.
idk yet its my first game
then you should probably just hard code all the abilties 😛
but I do have a lot of ideas
a lot of what's hard about this is actually the presentation of it
making vfx/sounds/hits/reactions/etc which can properly convey all of these things which your complicated and amazing ability system can accomplish can be a lot of work and very tricky
it's easier to convey things to players if they work consistently, but a very flexible system need not do that
yeah thats a later me thing
to polish everything
just want to get the systems down
ill make room for all of it but not implement it
Hey just for clarity, to run the "Actions" you'll need some ActionManager class that'll take in actions and then execute them whenever you want. This is basically the command pattern.
ah yea okay
if(Input.GetKey(KeyCode.LeftShift))
{
CurrentForwardVector = transform.up;
speed += 1f * Time.deltaTime;
}else if (speed > 0)
{
speed -= Time.deltaTime * 0.2f;
}
if (Input.GetKeyDown(KeyCode.Space))
{
RaycastHit2D hit = Physics2D.Raycast(transform.position, transform.up);
if (hit.collider != null)
{
Destroy(hit.collider.gameObject);
}
}
transform.position += CurrentForwardVector * speed * Time.deltaTime;
I want to make a space ship movement
when accelerated in a direction it should continue in that direction until the thrust is applied in a different direction
I have the part where it continues in a direction but I want a gradual change to another direction when thrust is applied
how do I do that?
the ability system is basically a separate project in itself . . .
well its integral to an arpg
Yep. You're basically making a little engine.
If you want some easy intermediate, do what Slay the Spire did.
thats why im approaching it with caution
Base Ability class with some abstract "OnCast" method.
Override that method, which creates those Actions I mentioned.
You skip the complexity from Effects and Targeting Strategies and whatever.
Just an ability class, an override, and executable actions to change the game state.
Don't ask how they did triggers.
only issues im thinking that might arise are setting ability damage/speed/whatever and having that react to things happening to the player such as debuffs etc
😮 i really want to know now though
'this card does 5 damage. when the target is weak, it does 5 damage again'
ah okay so conditionals
'every time you play a skill, gain 5 block'
"Cards" were their base class, and they had an overridable method for every event they cared about in the game. Many cards just have empty methods because of it. Whenever an event went off they just iterated through every card in the game and call some specific method.
When X happens, do Y.
haha that's amazing, i love it

You want a separate object to handle the "listening" of the X and making sure values are correct, and the Y is just a list of Effects again.
you see, beginners? just do what works and make your millions
Tbf they had Actions and a proper ActionManager and all that.
But their triggers were.... mmm
i figured becuase the sequencing works pretty well, queueing is smooth
but also it doesn't really work, if you watch speedruns there's all sorts of sequencing issues that can be exploited
See using my suggested setup, this could be solved with some ConditionalEffect. This effect takes in 2 sub effects and a "condition". When you ask the Effect for a an Action, it evaluates the condition and just runs whichever sub-Effect is relevant.
But again, this is pretty robust.
yep that's pretty much what i did in my slay the spire clone
And then you have to ask the question of "Well how do I feed in proper contexts, some effects care about different things in the game?"
and then you get into Blackboards and value grab bags and sdgjibghlrfdghmnteohmgkfdlgntmbrfgt
apparently I can't multiply the -transform.right in this line but is there a way I could use it anyway ? Here is the line : rb.AddTorque(-transform.right * 0.05);
and suddenly you're basically writing your own scripting language
so this is indeed a rabbit hole lol
but all my cards were fully data driven so i could serialize them and modify/save them out at runtime because apparently i'd rather waste time than release a game 
and then you just start convulsing
is there documentation for how slay the spire did this?
nah i gave up on that shit ages ago and my gamestate is a blob
embrace the blob 
YES YOU SEE THEN YOU JUST START PASSING THE ENTIRE GAME STATE THROUGH EVERYTHING BECAUSE FUCK IT
sure, scorll up 😄
this is the guiding light of ecs
make everything public but control access patterns
game state is meant to be queried
let it live happily in the light
is there an error? i'd post it so we can see what the problem is. also, what is 0.05?
I'll fucking query my fist through your face.
{
Vector3 newPosition = Vector3.MoveTowards(PlayerController.instance.transform.position, _position.position, _moveSpeed * Time.deltaTime);
PlayerController.instance.transform.position = newPosition;
Vector3 chestCenter = _position.position + (_position.position - center).normalized * 2f;
Vector3 targetDirection = chestCenter - PlayerController.instance.transform.position;
Quaternion targetRotation = Quaternion.LookRotation(targetDirection);
PlayerController.instance.transform.rotation = Quaternion.Slerp(PlayerController.instance.transform.rotation, targetRotation, _rotateSpeed * Time.deltaTime);
Debug.Log("Player Rotation: " + PlayerController.instance.transform.rotation.eulerAngles);
Debug.Log("Chest Position: " + _position.position);
if (Vector3.Distance(newPosition, _position.position) < 0.1f)
{
PlayerController.instance.SetState(PlayerController.State.OpenChest);
_animator.SetBool("Shake", true);
_movingTowardsChest = false;
}
}``` i cant seem to make my player rotate and face the center of the chest
and you are welcome to, as my face is simply a component of myself and all are free to read or write to it as needed 
noooooooo
0.05 is a double you need to use a float
here is the error : Assets\frontWheelMovement.cs(31,26): error CS0019: Operator '*' cannot be applied to operands of type 'Vector3' and 'double' and I'm trying to multiply -transform.right by 0.05 to get a very slight movement
as i figured. i mentioned 0.05 because you were missing syntax to make it a float . . .
https://imgur.com/aq68rOa is this relevant? this is how for honor tackled this
ok
hahaha they gave a whole talk on it, hang on
"So the "Modifier_SwordAttack" with a "Damage: 20" property would inflict 20 damage on the opponent if the Opponent is a ValidTarget. In addition, the Enemy would also take the "Modifier_BurnDoT" Modifier into it's Handler and run a Timer for a specified duration that deals a specified amount of damage to the Enemy. "
In this 2017 GDC talk, Ubisoft's Aurelie Le Chevalier dives into For Honor's modifiers system, a data-driven system that allows designers to dynamically create gameplay effects, that can handle anything from simply buffing/debuffing character stats (damage, speed, etc.), AI decision-making, areas of effects, and attack properties.
Register for ...
im wathcing that now lol
there are a lot of great gdc talks
that one i watched and then was like 'that's it?' but there were a few smart tidbits
keep in mind that these kinds of talks are solving Ubisoft scale problems which it would most likely be a waste of time for you to solve
yeah true, but the idea is still the same
they literally cannot have someone just open up the ability script and edit it because there are 50 people all working on the project at the same time, so they must split things up
you don't necessarily have to unless you are gaining from it
makes sense
Seems pretty close to what I was talking about. You can see similar terminology to what I was saying.
- Modifiers = Spells
- Effects
- Actor Selector = Targeting Strategy
- Conditions
I think the most important aspect of ability systems is just realizing that all abilities can be broken down into.
- When do I activate?
- Who do I effect?
- What do I do?
If all of these aspects are easily swappable in your system, you're gonna have a good time.
anyone about?
when dealing with the who do I effect part, is a good way to handle it to pass in a layer? so for example, an enemy can use a "player" ability and allow it to hit the player without having to change the ability
Like a Unity Layer?
sure, say im using an overlap circle or a collider
that i would modify
No I don't think that's good. Hide the Unity stuff in some derived class. For example imagine this.
public interface ITargetStrategy
{
public List<GameObject> GetTargets();
}
public class OverlapTargetStrategy : ITargetStrategy
{
Vector3 origin;
float radius;
LayerMask layerMask;
public ColliderTargetStrategy(Vector3 _origin, float _radius, LayerMask _layerMask)
{
origin = _origin;
radius = _radius;
layerMask = _layerMask;
}
public List<GameObject> GetTargets()
{
return ///Do Overlap Sphere and feed in those above variables
}
}
public class Spell
{
ITargetingStrategy targetingStrategy;
List<Effect> effects;
public void Cast()
{
var targets = targetingStrategy.GetTargets();
foreach(Effect effect in effects)
{
var action = effect.CreateAction(targets);
///Load your action into the action manager for processing.
}
}
}
it might be useful to have a concept of 'teams' and then if you wanted to, you could have a bitmask for whether something targets allies or enemies or both or whathaveyou
can I use a float to rotate a gameObject ? I'm to lazy to create a quaternion
wow thank you, very helpful
but that would just be one piece of the stuff above, where your targeting strategy could factor in the team or not
Ok now here's the PSYCHO SHIT. You see that cast method? Fuck it. It's for nerds and squares.
Make Spell just hold data.
Create a CastSpellAction and have that define what it means to cast the spell.
that's what i'd do
i think, i haven't actually made or thought about making an arpg so maybe in practice i would feel differently
so then create multiple " CastSpellAction"'s for each different spell
What're the different spell types you want?
create projectiles (different speed, formation, pierce, chain, etc), apply dot affects, ground effects, melee attacks (different shapes, windup times, makes character move), passives, heals, etc etc
i think most skills could be generalized under one of those
another thing to note, i want to make skill tree that can modify each of these skills
that would still be conssitent with this architecture right
A couple of these are different "types" of things, but I believe they can all be handled by Effects and Actions. For example your projectile could be spawned by a "CreateProjectileAction", which creates whatever prefab you want and then provides it with a list of Effects to execute whenever it hits/does whatever it needs. Then you could have a projectile that heals or damages or teleports or whatever.
Whatever your actions can do, it'll be able to do that.
this also turns out to be a good idea because by having most things be a projectile, you can tie visuals to that projectile even if it's not actually an active missile
Applying a DOT effect would definitely be an action, but youd need some DOT managing system to handle the lifetimes of these things. The DOT can again just create more actions when it goes off, so you can again create a DOT that does anything. Damage, heal, teleport, etc.
e.g. your summon skeleton spell might still want to shoot out a tendril of mist to where they are spawning from so that the player knows what's going on (a ground targeted projectile which triggers a spawn when it hits)
Simply put you just have Actions that spawn entities that do other actions 😛
and you can always have a projectile with 0 travel time
Modify in what way? If you have specific tiers of Spells with upgrades you know (like Slay the Spire), you could literally just create a new Spell that's supposed to represent the upgrade.
If it's really dynamic, you might have trouble.
this is way more common than you'd expect
couldn't the dot Action apply an Effect on the target which then is evaluated every frame?
so every target would be evaluating its list of effects to see if they apply
you can also combine it with simpler effects for that 'family' so that you can have 'bone spear rank 2' which shoots 2 spears and now they come back to you but also 'bone spear damage increased by 50%' which should affect all ranks
not 100% sure yet but it wouldnt be super dynamic
Actions are one time executables. Your "ApplyDotAction" would create some separate DOT object that'll be handled by some other system. That Dot object might have its own set of effects that go off on its timer.
can you clarify what you mean by Effects?
i tend to call those Auras copying WoW, but some kind of concept for persistent effects which tick is very useful
in my mind im thinking each action will have a set of effects that it applies to whatever it hits, then the hit target will evaluate those effects
So the way I imagine Effects are that they are "blueprints" for actions. They're the ones that evaluate the game state and decide what should be done. They just don't actually change the game state.
Actions change the game state.
so the actions would have the damage, cooldown, attack speed etc
the effects are just how the action applies those
Effect = 'thing that can happen in the game, in the game's terms, like 'damage can be done'
Action = actual state change which reflects that effect, which could actually be composed of multiple actions, like 'subtract 10 from State.playerHealth'
effects are more for 'design time' and can include conditions and extra context stuff to decide whether they should happen or not
if they should, then they get resolved into a set of actions
Dunno. Does the code actually run? Try placing a debug message at the end of the methods to make sure.
I know they sound similar, but trust me it's super valuable to separate the pieces that figure out WHAT to do from the pieces that actually do the thing.
this is that composition we keep harping on
You will like have shit like DamageEffect and DamageAction.
so the target will evaluate the several Effects to see if they should turn into Actions? like if the enemy is poison resistant, it would evaluate a PoisonEffect to false and not turn it into an Action?
there are a few ways to do it really
in practice you probably still want to trigger the effect but then RESIST! it so that you can provide that feedback to the player instead of just nothing happening to that unit
Yes that's one way to do it.
but you could do that at either end really
as in the "projectile" would evaluate if it should apply its Actions to the target instead
okay i appreciate it a lot, going to tackle this all tomorrow its 3 am lol
thanks for all the help
Back when I tried my hand at this, this was my DamageEffect.
public class DamageEffect : Effect
{
public ValueProvider<int> DamageValue { get; }
public ValueProvider<EntityData> DamageTarget { get; }
public DamageEffect(ValueProvider<int> damageValue, ValueProvider<EntityData> damageTarget)
{
DamageValue = damageValue;
DamageTarget = damageTarget;
}
public override GameAction GenerateAction(in GameContext gameContext)
{
int damageValue = DamageValue.GetValue(gameContext);
EntityData damageTarget = DamageTarget.GetValue(gameContext);
var damageAction = new DamageAction(gameContext.Source, damageValue, damageTarget);
return damageAction;
}
Don't ask what a ValueProvider is 😛
i have those too 🤝 gotta resolve dynamic values for stuff out of the gamestate so that you can do damage based on other things!
yeeeeeeeeeeeeeeeeep
Rabbit Hole
I do think that a sort of ECS-like structure is the best for these systems.
I think I reached a point where Actions weren't even doing anything.
sounds like you owe me a new FACE
a lot of my actoins do nothing or very little, and systems hook into them to actually generate the actions instead of having them be tied to the effect like yours
They just carried data given to them from the Effect, sent out an event, and then Systems would hook into these events and modify the game state based on that data.
yepyep
ITS DOOMED
it feels really nice because your features sort of live in independent slices
ya and the definition of what anything "does" can be swapped out
var entity = gameState.Entities.CreateEntity();
var damageEffect = new DamageEffect(7, new CasterProvider());
var healEffect = new HealEffect(5, new GameContextTargetProvider());
var eventValue = new GameContextValueProvider();
var boolProvider = new IntComparisonProvider(eventValue, 5, Comparison.GreaterThan);
var boolProvider2 = new IntComparisonProvider(eventValue, 10, Comparison.LessThan);
var andProvider = new AndProvider(boolProvider, boolProvider2);
var condition = new Condition(andProvider);
var trigger = new Trigger(EventHelper.AfterEvent<DamageAction>(), entity, condition, new EffectResponse(healEffect));
gameState.Triggers.AddTrigger(trigger);
var damageAction = damageEffect.GenerateAction(new GameContext(trigger, new Context(), gameState));
gameState.ActionManager.QueueAction(damageAction);
gameState.RunToCompletion();
Ya I was really down the hole.

but i understand...somewhere i have a sea of ContextProviders and ContextValueResolvers from long ago
It was kinda cool when it all worked.
Maybe I'll dip my toes back into it in the future.
yeah it sure forced me to learn how to use generics and stuff better than i knew back then
and then once i got it working i was like 'great now how can i avoid having to do this ever again'
✨ game dev ✨
If it wasn't OBVIOUS what this does, it creates a Trigger that heals anyone who takes damage for 5 if the damage value is greater than 5 but less than 10 🙃
to be fair this stuff looks worse in code than if you built an inspector to abstract hide away a lot of the ugliness 😄
Just a quickk quesiton. Im making a vr game still x_x. How hard would it be to code zero gravity like a space game
well you can set gravity to 0 or don't use rigidbodies and there ya go
oh
does that include if i wanna make certain objects float?
also wat abt movement like if i grab could i throw myself or will i need to code in something like climbing
i'm not sure what the xr toolkits include by my understanding is that they are pretty terrible
You'd need to code all that regardless of VR tbf.
well they might include some kind of hand pulling locomotion?>
VR dev isn't thaaaat dfferent other than the Camera being super glued to your head.
ye ik but im still rly new and still trying to understand
idk why i picked this stupid idea for my major
you should start by making a simple non vr game to understand unity
questions like 'how do i make objects float' don't really make sense and you're wasting your time thinking about them
agreed
what is a nice namespace for GameInput? 
can it be gameinput also?
not sure how namespace works
tru, the only reason i ask simple things is because i wanna make a space game with some puzzles. Since this is for my major work for school and will go towards my final mark when i leave so Im also on a time limit
rip
Look up in the docs.
But this is far from a simple thing. "How do I make objects float" is too broad of a question, with many answers. You should follow a simple tutorial, get to know VR development.
Then get more specific.
But i'd start turning gravity off with 0 drag 🤪
This is not for VR, but teaches a lot about zero gravity environments
https://www.youtube.com/watch?v=fZvJvZA4nhY&list=PL-hj540P5Q1hPXuhIV0uUAsSNsBop4449
In this Unity Tutorial series I will go over how to set up Rigidbody spaceship movement, how to use cinemachine as well as how to use the new input system.
This is video 1 of the Space Sim Unity Tutorial series!
Free skybox pack: https://assetstore.unity.com/packages/2d/textures-materials/deep-space-skybox-pack-11056
Free spaceship model: http...
Hello everyone Im having some trouble here and i've been stuck for alteast 24 hours on this My item prefab slot is a button with a text gameobject child and a image gameobject child. I keep getting this error ""Chest Content is not assigned.
UnityEngine.Debug:LogError (object)
InventoryItemController:TransferToChest () (at Assets/Scripts/Inventory system/InventoryItemController.cs:97)
UnityEngine.EventSystems.EventSystem:Update () (at Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/EventSystem.cs:514)
" This script https://paste.ofcode.org/EZtNcFt6vLThDC8t8xRZiG < is trying to call the TransferToChest method in the OnClick fied of the inspector in the button UI. now it makes sense at first, because in order for the item prefab to be instantiated initially it needs to be interacted with from the world "scriptable object" then it gets instantiated with this code https://paste.ofcode.org/TquWcJPGREU4wKYx6fKBsG < and then the item prefab slot spawns under the content in the Canvas of the inventory. Now im trying to transfer it to chest using the InventoryItemController with an onclick (double click item prefab). I assigned all the properties in the inspector and it gave me this error up above. But It wont let met actively assign data in the prefab of the item because when the game starts it is not instantiated yet. so the properties prefab are not there on start up. basically the gameobject field in the button click is empty on start up because the item hasnt been instantiated yet. so I created this script >https://paste.ofcode.org/iJP3bxYEkqjCsAnXhW9HdY to try to instantiate all objects on start and still no luck. if anyone can hlep it would be great
I see nowhere in that code that calls SetChestContent on InventoryItemController
no it only calls for transfer method because im setting the chestcontent in another script and calling it in this one because unless it is initailly instatiated on play (which its not) it wont let me assign content in gameobject field
I have to assign it manually in play mode
in the inspector after it as already instatiated
so why are you posting code that is irrelevant to your problem? Post the code where you call SetChestContent
im trying to learn here is this not beginner channel?
Chestcontent is not beign assigned because there is nothing to assign it up on start up
how do I fix this?
how can I tell you if you don't post the correct code?
AI Generated code?
I mean not all of it but some of it
you know we don't provide help for AI code
why what its helping me learn wtf
server rules
Seen too much of the crap it generates. It's pretty obvious
Huh, interesting
Hey guys, I'm moving a game object that is a child of HorizontalLayoutGroup (using OnDrag and changing the loacalPosision), and when OnEndDrag is called I'm trying to reset the position of the object to the position that it started with, I tried storing that location and manually change the localPosition, but it's not resetting to the location that intended When I was trying to figure out I noticed if I paused the game And just moved that child with the mouse it will try to move but will rest to the location that I want (the inforced location by the laoutGroup), Any Idea if there's a function that I could call It will reorder the children?
Kinda sad ngl that game dev and programming may be taken over by ai
what is even sadder is that young aspiring devs are resorting to using this crap instead of putting in the effort to learn properly, it says a lot more about them than the AI tools they are using
Facts but ive learned more using the AI so whatever helps you learn right
Yeah, I’m pretty young, currently working on my first game and I’ve learned programming techniques using scratch, codecademy, and an ungodly amount of googling
you're lucky you've got Google, when I was learning all we had were very expensive books
Huh, learning programming from a book, sounds…interesting
Idk, my dream job is to be a game dev so I’m trying to build a solid foundation
It’s hard to use AI if you don’t already know how to code. Most of the time what it gives you is not what you want. Sometimes you get lucky. Sometimes, though, it gives you something that looks right at first glance but actually takes longer to fix after. Problem with AI code is where the programmer comes with it and doesn’t understand why it doesn’t work and then can’t answer any of the questions this server has for them because they didn’t write it and don’t understand it.
Imagine the time you spent on Google and then times it by 100, that's what I'm talking about
Oof
Well, it’s a sure fire way to learn, if your spending so much more time on it - I just hope using google doesn’t form cracks in my programming knowledge
very well said
I agree, to an extent, the same applies to YouTube tutorials such as “making your first unity game” and such. You have to learn how to take away information and experience from the video, rather than copying down whatever it tells you
oh, it will, the benefit of using books is that even when you are looking for something specific other things, releated or non related will catch your eye and be remembered for future use
The best way to learn imo is to try to do a thing yourself and look up everything you need to know to do that thing on your way.
That way you are the agent of creation and need to learn from your mistakes.
Exactly, that’s how I learned dictionary’s, delegates, is statements, and a lot about unitys workflow
It’s a great way to learn and apply new concepts quickly and make them stick in your brain
Is there a function to get a list without specific element in a way it doesn't affect the original list?
You can use LINQ’s where() function.
LinQ, but please don't
you have to deep copy everything
I do hear a lot that linq is super slow and should be avoided but I don't understand why and how it is slow?
I mean yeah can manually create a function with addrange and all, just wondered if there already existed a method
It generate tons of garbage and it has to gate check everything, 90% of what it does is unnecessary overhead
It is slow because it creates a lot of objects dynamically.
It’s not as bad as people make it out to be, especially where you use it for one off code or whatever.
You generally don’t want to use it for highly repeated code. It should also be said that for a small project while learning, the code brevity you get from linq can be an advantage and won’t meaningfully affect performance.
getting sub-list of list is just shallow copy, if you dont want to affect the original list, you have to deep copy everything (unless you just want the "list" itself not to be changed, not the objects inside)
to start with why List -> List? Why not List->Array as you know the size of the destination?
Fair point, I guess I'm just used to doing list everywhere 😅
List is much less performant than Array
I think tarodev debunked it earlier? Both perform almost same?
I mean with respect to speed atleast
then he is wrong under most circumstances
I might be misremembering too, I'll go recheck
you can write code as
public int Filter(T[] original,T[] results ,Func<T,bool> predicator){}
```then return the count and store the values inside results
https://learn.microsoft.com/en-us/dotnet/api/system.array.findall?view=net-8.0
the one of ms returns an array
Hey, So small question i'm making a game and right now i have a public GameObject variable that i want to assign but through a script, not through the inspector. How do i do that? been a little while i've been looking and saw nothing sadly.
You need to get a reference to that game object somehow.
GameObject.Find, if you really must
There are many ways to do that so it depends on circumstances.
Right now this is what i have
i get the GameObject variable and try to make it equal to this game object but sadly it don't really work
this is kind of weird... you are saying test is the blueportal on the same gameobject, but then you are also saying that test's orangeportal is the same gameobject
and doing it in Update is just wrong
Nvm it wasn't about array vs list, it was linq vs loops to filter lists
My bad
both scripts are on the same gameobject so why would you need to inform them of that gameobject?
doing it in the update cause just doing some test don't wana call the script each time i shoot my portal right now
but that will make absolutely no difference. but anyway your code looks ok as long as both components are on the same game object
oh have to make it on both?
im guessing you are getting an NRE
nope it unassigned not null since it a public game object
best show the actual error
If you try to use unassigned variable, it will still give null reference error 
"UnassignedReferenceException: The variable orangePortal of Blueportal has not been assigned.
You probably need to assign the orangePortal variable of the BluePortal variable of the Blueportal Script in the inspector"
I used LayoutRebuilder.ForceRebuildLayoutImmediate(_layoutGroupRectTransform);
for the RectTransform in the layout group that is in the parent
if anyone will has a similar problem 💙
oki thanks for the info
and that happen each time i walk in the blue portal
So your GetComponent<Blueportal>() is failing
probably because you are looking on the wrong game object
they are not on the same gameobject orangeportal script is on the orangeportal and blueportal scrip on the blue portal
so why are you looking for it on the same gameobject?
"GetComponent" gets the copmonent on the same gameobject
ooooh yeah did not think about that X) gonna try something else
if you call "GetComponent" from "OrangePortal", it will get the component of "BluePortal" on the same gameobject as "OrangePortal"
completely forgot about that yeah
Also, style police moment. Keep your naming consistent. It hurts to type OrangePortal and Blueportal
oh okay sorry
i don't usualy ask for help on the discord and just look at the documentation or tutorial
one common way to get references like this is to have some manager component that holds references to components you need. all gameobjects that care about that manager have a reference to the manager and can ask for whatever they need. another way is to query the scene geometry like with a raycast or a collider. another way is to use find.
there are a lot of tools you can use and the appropriate one depends on the circumstances
oh wait i found one of my big problem and mostly why it did not work is i completely forgot to add my orangeportal script to the orange portal
oh okay thanks for the info
will be usefull in the future
Trying to make a toggleable world light on top of a flashlight, but I keep getting an unsassignedreference errow how to fix?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
public GameObject target;
public GameObject fullLight;
public KeyCode key = KeyCode.F;
public KeyCode lights = KeyCode.Colon;
void Update()
{
//target.SetActive(Input.GetKey(key));
if (Input.GetKeyDown(key))
{
target.SetActive(!target.activeSelf);
}
if (Input.GetKeyDown(lights)) {
target.SetActive(!fullLight.activeSelf);
}
}
}
shouldn't have pinged my bad
np, also screenshot the inspector
21, just found it I'm calling target.SetActive again instead of fullLight nvm

target.SetActive will cause an error if target is null
yep, that makes no differene even though it is wrong
fullLight.activeSelf will cause an error if fullLight is null
Any use of the member access operator -- . -- can cause an exception with a reference type
(along with the indexer operator, [])
I see, then what method should I use to attach those pieces of code to their respective GameObjects?
Just make sure that both are assigned in the inspector.
the inspector
since these variables are public, they're serialized by Unity by default
they seem to be in the GameController object
this means they will appear in the inspector, and that Unity will remember the values
Perhaps an object is being destroyed, or you have multiple copies of NewBehaviourScript
You can check the latter easily
Search in the Hierarchy view with this:
t:newbehaviourscript
oh yeah I have 3
That'll do it
Clicking on an error in the console will (often) take you to the offending object in the hierarchy, by the way
(single-clicking)
didn't know that thanks
one last thing though the Lights toggle doesn't work
The method takes a second argument -- the "context"
you can pass any unity object in
here's an example of how I use that...
if (category.label.IsEmpty || string.IsNullOrWhiteSpace(category.label.GetLocalizedString()))
{
Debug.LogWarning($"{category} has an invalid label", category);
}
category is actually an asset
clicking on that log entry takes me to the bad asset in the project window!
oh that's neat
not getting any errors for it but my other method reading a colon in isn't working at all
you should use Debug.Log to see if the if the colon key is being noticed at all
The problem will be that ALL instances of the script will be trying to do the same thing
nope don't think it is being noticed
huh, I see now
why have this script on more than 1 game object?
not sure, just thought it was possible to save space and keep everything under an "activation" script
but by all means if that's not best practice I'll make a new file
I mean if you are checking for specific keyboard input it makes sense to only do that in one specific place
would anyone here be able to help me with a chunk of code i js cant get right?
maybe, if you actually post the !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.
yes, sorry im new to the server i wasnt sure this was the channel for it
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hello. I'm getting warning while trying to simulate animation on y axis. If anyone can help me I would be super grateful I'm down to share more details.
basically, my wasd movement is all good its just the gravity and jump i need now. i can move up and down slopes but when i try jump yvelocity.y returns NaN
Guys can I send a small 5 sec vid for my problem?
I m trying to move an object with Getaxis, its working fine just that there is some unnecessary drift after I let go off the key. How can I remove that
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlaneController : MonoBehaviour
{
public float speed;
// Update is called once per frame
void Update()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
transform.Translate(Vector3.right * moveHorizontal * speed * Time.deltaTime);
transform.Translate(Vector3.forward * moveVertical * speed * Time.deltaTime);
float clampedX = Mathf.Clamp(transform.position.x, -20f, 20f);
float clampedZ = Mathf.Clamp(transform.position.z, -20f, 20f);
transform.position = new Vector3(clampedX, transform.position.y, clampedZ);
}
}
GetAxis has some built in "smoothing". Use GetAxisRaw if you don't want the smoothing
Also rather than calling Translate twice have you considered combining everything?
Vector3 moveDir = new(moveHorizontal, 0, moveVertical);
transform.Translate(moveDir * speed * Time.deltaTime):```
Guys why do my gizmos change position as the window size changes
These codes are everything related to it
topLeft = new Vector2(transform.position.x, transform.position.y);
bottomRight = new Vector2(bottomrightX, transform.position.y - 23.5f);
colliders = Physics2D.OverlapAreaAll(topLeft, bottomRight);
Gizmos.DrawLine(topLeft, bottomRight);
got it, it worked with GetAxisRaw, thanks
Your gizmos are probably not at the same z position as the game world objects (they're at z == 0 based on your code)
and you are probably using a perspective camera
like i should try to make the objects y=0 for instance
z not y
just makes sure both vectors in the DrawLine have the same z coord
I did both i also changed my camera
you changed your camera in what way
i made it orthographic
also where does bottomrightX come from
i assign it
then you should be all good now
its still not working 😭
its not a z thing since they are vec2
Did you happen to build your game out of UI elements?
i.e. is everything happening on a canvas/
yeah could be a overlay canvas
yikes. Well that's your problem
your UI is rescaling as you change window sizes
it shouldnt?
the gizmos are not moving
no, UI is for UI
gameplay should happen in world space
Uh.. anyone? 👀
but the problem is the plant i spawn is a child of a UI object
You are trying to use some animator parameter that you didn't define in the animator
double check the spelling of your parameter
ok and lets say i take them out of UI what difference does it make to my game?
it makes your objects have consistent world space positions
fixes this problem
and then your gizmos (which also have consistent world space positions) will not not appear to "move" when the screen is resized
but otherwise just different workflow
can still accomplish what you want, just might have some extra logic for fitting the camera to things
Also all physics, lighting, code etc generally operates with world space coordinates which will now make sense
ok and if everything is out of the canvas and i want to rescale my window theyll all like resize?
no reason they could not all be done with sprite renderers and maybe a tilemap
like all the objects i take out of it?
i just noticed that my objects are still detecting mouse hovering etc when behind ui elements, is there a quick fix to that at all?
depends on how you detect that
but are a few ways
How are you detecting the mouse currently? The best solution is to switch from whatever you're doing now to using IPointerEnterHandler etc
so OnMouseEnter etc
yes, so switch to the Event System stuff
yeah use the EventSystem and its handlers
and make sure you have the correct kinda raycaster on your camera for it
once done this will be automatic
is it just a case of including "using unity.eventsystems" and then changing the OnMouse functions to pointer ones?
no, you need to actually implement the interface(s) and if you are using world space objects then your camera needs a Physics Raycaster component
would that be physics 2d raycaster for a 2d game?
do this objects have 2d colliders on them?
yes
if so yes
once setup, event system will cast with GraphicsRaycaster to check for UI hits, if no UI handles it, then it will cast via the physics 2d raycaster
you mean this bit?
that's part of it, yes
yes those are interfaces, after you add them, you implemented the methods they require
so for IPointerEnterHandler it requires you to create a void OnPointerEnter(PointerEventData eventData) method
i see
onmousedown would change to public void OnPointerDown(PointerEventData eventData)?
yup
IPointerDownHandler
if your ide is setup correctly, it should create the methods for you after extending from the interface
like my will go red after adding it, then offer a quick fix
yeah that scared me for a second but actually putting the methods in fixed it
yeah interfaces are a useful concept
they are essentially a contract
if something is a IPointerEnterHandler its more a contract saying it implements a method, and can be asked to use it later without needing to know what the exact type is
private const Vector2 PLAYED_CARD_SHADOW_OFFSET = new(5f, 5f);
Are vectors runtime dependent? I.e. do I have to use two float constants instead?
Constant initializer must be compile-time constant
it's not that the vector itself is "runtime dependent." you need to pass in a compile-time constant. "new Vector2" is a dynamically created object
Ahhh yes that would make sense
@spiral narwhal no const on the vector types since they are just structs
you could do a readonly static for similar effect
private static readonly Vector2 PLAYED_CARD_SHADOW_OFFSET = new(5f, 5f);
ive made a movement script but it works even if i take my finger off the movement key
any hlep?
Code?
without seeing the code, how can we help?
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
Vector2 inputVector = new Vector2(0, 0);
private void Update(){
if (Input.GetKey(KeyCode.W)) {
inputVector.y = +1;
}
if (Input.GetKey(KeyCode.A)) {
inputVector.x = -1;
}
if (Input.GetKey(KeyCode.D)) {
inputVector.x = +1;
}
if (Input.GetKey(KeyCode.S)) {
inputVector.y = -1;
}
inputVector = inputVector.normalized;
Vector3 moveDir = new Vector3(inputVector.x, 0f, inputVector.y);
transform.position += (Vector3)moveDir;
Debug.Log(inputVector);
}
}
move Vector2 inputVector = new Vector2(0, 0); to inside Update
alteranteively just do inputVector = Vector2.zero; as the first line in update
but... can you see why? You're not ever resetting it
oh that makes sense
because once i edit it it doesnt stop cause it doesnt update when i take my finger off
thanks
is it better to use Quaternion.LookAt or is it better to just to use Trigonometry and Rotation to make an object rotate around something?
like this
Im lazy so I use lookat
you can also run into gimbal issues with Quaternion.Euler though
is this for a 2d thing?
is he the ancient wizard that makes unity?
yea
i want to make a gun that rotates around the player
ah, that's fine then since you only need to rotate on one axis
your code seems fine in that case... there's a constant like Mathf.DegToRad btw, I assume that's what you're doing
system Math uses doubles, unity math uses floats
aaah
not big, Unity's has a few more things, I guess
thankyou guys
Unity's actually uses System.Math under the hood, so in a sense it too uses doubles for many things 😄
unity math is just system Math but with fake mustache and a trenchcoat
exactly
I hate that they tried to be smart and implemented Mathf.Sign to only reutrn +1 or -1, and not 0 when input is 0...
okay, not hate, but highly dislike 😄 took me some time to fix a bug, because I didn't expect the function to behave like that
I mean, 0 is positive
Math.Sign return 0 for 0 🤷♂️
as opposed to -0 which is negative
my math teacher would shake her head in disagreement if she sees this
a light shake
while there are two 0 representations, there shouldn't be much difference... I'm not sure -0 would actually give you -1, but am now curious
Can someone tell me why it isn't playing music from my audio manager
In computing, there are positive and negative zeros, as Steve was alluding to. In floating point arithmetic, only positive 0 is actually achievable, but there are two zeroes as far as your computer's ALU is concerned
Nothing here actually plays any audio
Your Play function searches for a sound and then does nothing with it
There is nothing of the sort in any of the code you've posted
Wait we can add multiple audio sources on same gameobject and have it work perfectly?
As long as you have some way of differentiating between them because GetComponent will get one at random (actually whichever one has the lowest GUID which is practically random as far as the human is concerned)
In this case, since they're stored in a list as they're added, you can properly reference each individual one
Yes yes
idk why it didnt show up in the file
Maybe I didn't save it
Didn't know that, that's cool
Try saving and running it again
well, at least in the Editor, Unity is returning 1 for Mathf.Sign(-0), so yeah - it's a sad implementation 😛
Sign explicitly says it returns 1 for 0
that is true, but it's weird, because it's not same as Math.Sign, and most things in Mathf are wrappers around Math
so why change this one to what I'd call random behaviour, instead of naming it something else
anyway, not the end of the world, just kinda weird if one is used to Math's implementation
Pretty sure there's no actual way to make -0 as a float
-1f / float.PositiveInfinity is a 0 that if you ask float.IsNegative returns true, that's as close as I could get 😄
it wouldn't print as -0, but float gets the weird point of what I'm trying to do 🤷♂️ 😄 and Mathf.Sign doesn't... which is normal, it treats both 0s the same way and returns 1... which to be fair is what it says it does, just doesn't match Math's behaviour 😄
is it possible to make a general script variable, and then have that variable be assigned any script in code?
as in, a non-specific script
What is the usecase?
use case heavily depends on how to approach
like got static, got singleton's, got SO's everything could reference
Component is the base class. But sounds like maybe your problem can be solved in another way
yes, static class, static variable
i have two different tower types with two separate scripts, i want to check which script is attached to a selected tower (whether its towertypeA or towertypeB) and then assign the script to a selectedTowerValues variable
selectedTowerValues would be the "non-specific script variable" in this case
since you have a concept of selectedTower
i would feel that what you really want is a script that holds reference to all towers, and defines which is "selected"
this is what ive thought of but im not sure if it will work
Do the tower scripts inherit from the same base class (not counting monobehaviour)?
unfortunately no
ok, and if that case passes what do you wnat to do with it
That could be useful. Or using an interface
so if i went that route id have to change quite a lot of code
so give them a common base class
or make a interface for them
that they all implement
Probably better than digging your self into a deeper hole 😄
maybe 😭
inheritance?
like TowerBase is a new type
then you have a class BallistaScript : TowerBase {
and others
Inheritance (sharing a base class) is one option, interfaces is another
interfaces are generally more ideal if there is no shared logic
but also are a pain to use in unity if inspector referenced
so also got the option of a abtract class as a base
public abstract class BaseTower : MonoBehaviour { }
public class BallistaTower : BaseTower { }
public class CannonTower : BaseTower { }
for example
then BallistaTowers and CannonTowers could all be stored in the type BaseTower
then could type switch later
Adding an interface at a late stage will be a PITA as you will have to seriously mod the existing code. Adding an abstract base class is the path of least resistance
would also put any common logic in the base since its the stuff you could access without a type cast
wouldn't this work as a workaround - I know it's not good practice but I think I would get really demotivated if I had to change so much
yes
so that could work, but giving them a common base class i fee ls cleaner
it definitely is, but I haven't experimented/practiced with that before so I feel like it would lead to a lot of hours of work for me
switch (selectedTower) {
case BallistaTower ballistaTower:
break;
case CannonTower cannonTower:
break;
default:
throw new ArgumentOutOfRangeException(nameof(selectedTower));
}
other nice feature of the common base class, is using type switches
though if dead set on your GetComponent approach
please use TryGetComponent instead of calling it twice
what happens if TryGetComponent fails?
Where could I write single variables, like setting a projectile's owner through a GameObject variable?
if (selectedTower.TryGetComponent(out BallistaScript selectedTowerValues)) {
class baseClass {
static int selectedId;
void SetSelected() { selectedId = GetInstanceId(); }
bool IsSelected() ( return selectedId == GetInstanceId(); }
}
it returns a bool if the thing exists or not, then sets the component on a out param
so that one line both checks if it exists, and if it does then assigns it to the selectedTowerValues variable?
Yes
if (selectedTower.TryGetComponent(out BallistaTower ballistaTower))
{
// do stuff with ballistaTower if it exists
}
It CREATES a local selectedTowerValues
To be clear
Leave out the type if you want to assign it to a class member variable
in that case would want a new one
since it would be a different unrelated type for each case
Yeah, I didn't see any of the previous stuff. Just wanted to make that clear for any future use.
i still think the common base class is the approach that should be used
absolutely
since that lets you have logic that is for all things of this category
then lets you cast to the concret type if you need to handle per type edge cases
like this?
Looking back at the conversation, I agree too. It would make things far easier to handle
yes
im really regretting not having both towers use the same script now lol
but this seems to work as a workaround
thank you
it would not be hard to literlaly just make a base class for all towers
then have both of them extend from it
im not sure how that would affect the rest of the code I have though as it's probably a mess
initially it would have no effect
but would let you gradually move stuff into the base class you want to share between both as you want
and allow you to store both of the tower types in a field of the base type
and cast to figure out what type it is
Hi, does anybody have a script for auto card positioning like big cards games have? It would take forever to do it by myself to look good.
I mean in hand
You draw a card and it is getting placed somewhere, different depending on amount of cards you already have in hand.
like here, the position of cards is different depending on how many cards one have
that is not very hard to code
just a wee bit of math, and would best be done per use case
It's not that hard to code bro...barely 10-15 lines of code
there will not be a pre-made script that does exactly what you want
no one gonna hand out code here tbh
really? i thought of many, many more
its just modifying a position based in how many cards you got
its just a tiny bit of math
ugui could probably do most of the work, but I know hearthstone does everything custom
would first just make it space cards properly based on count
like figure out a offset, which is the card width + padding
add that offset * card number to the x position
there's one other consideration and it's smushing cards closer if you don't want a proper gap
the gap could be a ratio based on the total count though
gets larger to a max with fewer cards
gets smaller or starts to overlap with more cards
all in all, what you want is really just math, and is simple if you break the problem down
actually doesn't look like they smush on the board there, but hearthstone does
in hand however they probably do
Hey @gosthir i also struggled for the same. I tried buildinga grid system, but could not figure out in 3d. 2d is in built
so foreach active card just move position by card_wight to the right, and every next card -card wight * times_it_has_been_decreased right?
Hello it's me again.
How can I customize JsonUtility's serialization of certain field of my class ?
For example I have a class Item :
public class Item : ScriptableObject
{
public string Name;
public string Description;
public int Value;
...
}
And a class ItemSlot :
public class ItemSlot
{
public Item Item;
public int Quantity;
...
}
Both are used in
public class Inventory : ScriptableObject
{
public List<ItemSlot> Materials;
...
}
How can I save the Inventory in a json ?
I have tried with this method
public class Inventory : ScriptableObject
{
...
public void Save()
{
// Serialize this player Inventory as a string in json format
string saveData = JsonUtility.ToJson(this,true);
BinaryFormatter bf = new BinaryFormatter();
// Get the string representing the path to the save file
string path = string.Concat(Application.persistentDataPath,savePath);
FileStream file = File.Create(path);
bf.Serialize(file,saveData);
file.Close();
}
public void Load()
{
if(File.Exists(string.Concat(Application.persistentDataPath,savePath)))
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(string.Concat(Application.persistentDataPath,savePath),FileMode.Open);
JsonUtility.FromJsonOverwrite(bf.Deserialize(file).ToString(),this);
file.Close();
}
}
}
I could save & load when I'm still in the unity editor.
As I left and reenter the unity editor and loads, the item are not recognized.
The Image is what the json looks like.
I have an Idea of making an ItemDatabase containing a dictionary<int ID,Item> that can gives me the Item when providing the ID of said Item.
But I don't know how to let Json Serialize only the Item's ID and not the InstanceID
dont save by the instance ID, either save by asset ID or generate an ID yourself
the instance id is because they are trying to save out a whole SO
really if this is for save data no reason to have it be a SO and not just a regular struct or class
ScriptableObjects are really for cases where you want to treat something like a asset
I made a ScriptableObject to create a lot of Items faster
if you don't need to write unique data, but only structure it by SOs, ID lookup to SO is a fine idea
Make Inventory a regular class
and Item
As for custom serialization https://docs.unity3d.com/2021.2/Documentation/Manual/script-Serialization-Custom.html use this or make separate DTOs
also ontop of those issues, no reason to use the BinaryFormatter
oh ok
If items already exists as SO's for other reasons can keep them
but SaveData i would make be its own thing
maybe it has a ID to the SO's you make
then can find the correct SO to reference by putting them all in a Dictonary with a id as a key
how do I say to JSonUtility to Serialize the Item's ID from a dictionary instead of it's InstanceID?
you make it your self
For anything deriving from unityEngine.Object, JsonUtility is going to serialize the instance ID only
you dont. JsonUtilty cannot serialize dictionaries
make it a field (for the ID), or use AssetPathID
would reference all your SO's in one spot shove them all into a Dictonary by name
use a different serializer, or don't serialize a SO
then save that name in your save data
then you can use that to look it up later on load
alos yeah would not use json utility
much better tools for the job
you don't need to serialize a dictionary anyway, the mapping of ID to Asset should be known on awake
but yeah the data you are saving and loading should not be the whole SO
but just a regular struct or class inside of it
I have this peice of code of here that is connected to a 3 button slow, medium, fast but every time I change scenes the variable set force always equals 0 and i dont know why
and on the other way, if my Items and Inventories are not ScriptableObject, JsonUtility will not get any InstanceIDs but the actual field (int, string, ....)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FrameRate : MonoBehaviour
{
public KeyCode framerate = KeyCode.I;
public bool showFrames;
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(framerate))
{
showFrames = true;
while (showFrames == true)
{
Debug.Log(1 / Time.unscaledDeltaTime);
}
}
}
}
Is there anything glaringly wrong with this or is it a hardware issue? Unity keeps crashing whenever I enable it
well how is this surviving scene reloads
there is not DontDestroyOnLoad or anything
no
and this script is connected to another game object in the next scene where i want this code to work
well not sure what its even trying to acheive but yeah this would freeze unity
with a infinte loop
because my first scene has a settings menu wich changes the foward force and but then when i load the next scene it says the foward force is 0
and so is the varible setforce
and the first scene stays loaded the whole time and this object is never destroyed and recreated?
it is expected your unity freezes because of the while(true)
i mean no i think the script is set in a panel on my first and on the next its set on another game object
is that a problem?
and whats the expectation, when you set it the first time its only on that once instance of the script
if you loaded a new scene, and the old instance got destroyed that value is now gone
like i am not even sure what you have going on
but sounds like it is part of scene one then you load scene 2
So uhh, any help?
which would destroy everything in scene 1 if it was not a addative load
i will show a picture of my code
i dont evem know what that means
no is that even possible
so there is your problem
look it up.. Additive scene loading
when you load scene 2, everything in scene 1 was destroyed
so when you return to scene 1, its all back to its defualt values
yes but what if I have my game manager that is a prefab
and I put that script on my game manager
will the values still be destroyed
not enough detials given to know
if you want it to not get destroyed you have to make sure that it will not
so either put it on a object that is DontDestroyOnLoad
or use addative scene loading
ok
when you load a scene, everything from the previous scene is gone
unless you tell it otherwise
wait i will look into it put just so i know we are on the same page im going to explain it more thoroughly
and yea u can load two scenes at once.. its like putting a drawing with a transparent background on top of another drawing..
it'll all exist (to you) in one place
here is my setting menu with my 3 buttons wich is connected to that script I showed you previously. that script is sitting on the game manager also ignore the console
as you can see the game object has not changed
simplest solution is to stick it in a DontDestroyOnLoad(); as mentioned above
ok
thank you
these are 2 different scenes
i did not know that existed
you'd always have access to it
its not the same object
does do not destory on load only load once every scene
likewise to void start or void awake
no, you have to ensure uniqueness if you need it
there is nothing to prevent you from getting more then one
can you show me how
DontDestroyOnLoad(this);
so dont destroy on start is not a function
u can put it in start or awke
well with gameObject
this is a component, it only accepts a top level game object
or gameObject
ahh gotcha
i need to refactor then.
ive been under the illusion that when u do anything to a component like DDOL the gameobject just go with it
when u load up the scene you'll have a new gameobject and u can uncollapse it and you'll see ur gameobject that u used DDOL on
i might be wrong, it might automatically get the Go
since its signature is UnityEngine.Object
i think it does.. b/c i didnt notice it
does not work
and i have a few DDOL
but it applies to ta GO not a component
whats setforce?
no do it to the whole gameObject
DontDestroyOnLoad(gameObject);
u want the script/ gameobject
Don't you think it might be a good idea to go and read the DDOL documentation before trying to use it?
how would i do that with the game object
sorry about asking these sillly questions
im a very big begginer
he just told u. thats the line u need
it'll not destroy the entire gameobject that the script is sitting on
and then u can remove ur gamemanager prefab from all ur other scenes.. b/c it'll already be there
it'll look like this.. and ur gameobject will be under the DontDestroyOnLoad object
like this
well.. if ur reference to gm is the gameobject u want to stick around then yes
what is being said.. is to put it in the script OF the gameobject u want to stick around..
then gameObject just references the script ur working in
i swear i think i have autism
public class ControlTower : MonoBehaviour
{
private void Awake()
{
DontDestroyOnLoad(gameObject);
}```
this would ^ cause the ControlTower script and the gameobejct that holds it to be NOT destroyed
game manager has more than one script
every script attached to that object will be not destroyed
the the object game manager has more than one script in this case
u may want to rethink ur setup.. and have only certain scripts on that gameobject
Objects are marked DontDestroy. That's why you can't pass in a component
The whole object will be a DDOL
i think i will call it in the script game manager later on but for now i just want this to work
(I'll just insert my standard "DDOLs suck btw" comment 😅 )
what is ddol
DontDestroyOnLoad
There's no better way to make an object persist between scenes
fair, it's just rarely needed to make game objects persist between scenes imo... and makes restarting scenes much easier when you don't have random objects go between scenes
depends on your approach i tend to never use it
tend to have a init scene with all the important stuff i want to keep a around
then that will do addative loads
additive scene loading is gonna be more confusing to him than ddol
i am not suggesting somoene new does addative loads
toggle on/off framerate count
I think I need an off toggle?
well currently its a freeze your game button
It really depends on your scene structure. If you don't do additive scene loading it can be a good idea to have a single DDOL for persistent data like your saves and settings
there is not reason for it to have the while loop
let me try sans loop
thats how i do it too.. got a preloader scene that does everything and then sticks around for hard references
That (persisting data and settings) tends to not need scene-stuff, so I'd keep it as a a normal singleton or one could use an SO as well
yeah its also a side effect that generally have like 5 or 6 scenes going at a time
i havent gotten that involved yet. but its possible 😄
for both technical and workflow reasons
SOs have the problem of behaving differently in editor versus builds, and a POCO singleton doesn't have an inspector to mess with
update nothong works my player is not moving
find it so amusing how you guys need a acrynom for a regular object
is it 0 before u press play?
no
because it set it in the settigns menu to be 2000
and then i load the next scene and its 0
Share the updated code
Instead of sending screenshots, send !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.
!screenshots
No
Be mindful, if someone requests your code as text, don't send a screenshot!
In your second scene, search t: SettingsMenu in the hierarchy and show what comes up
here
Setforce is private variable, and isn't initialised so by default it will be 0
did not do it
so just mak it public
how do i search
while in playmode
with your keyboard
i will just send a ss with my game running
type the letters which will appear in the searchbox
Send a screenshot with your game running, in your second scene, while searching what I said to search for
I am not sure if this is the appropriate channel for my question but I am having problems with my Light 2D component, it seems like it does not want to affect my grid when put to Global.
Okay now this screenshot but with the search in the box like I asked
assuming its the target sorting layer is not correct
It's put to default which my grid is on but I'll take it to #archived-lighting from here
where do i search where is the search box im sorry for being an idiot by the way i just cant seem to undertsand
idk i probably put 2 by accidnt
i removed that one
Even after that value will still be 0 as it's private variable which is not initialised
it sounds like they are setting it from logic in there menu
and it is supposedly being set to 2000, then resetting on scene load, but it's a DDOL so it shouldn't initialize again
the problem is they unload the whole object and reload it and expect it to be teh same
still dont work
Doesn't look like that from this screenshot atleast 
Which means there's most likely a second copy in the scene that has 0, and the one that had a value changed isn't the one that's logging 0
well 2 coppies of it there
As I said
which means it existed in more then 1 scene
There's two copies of it.
One has 2000, one has 0
You want there to be one instance of this. Ever.
so the ddol makes it so i only need one game manager
Not a single method is called from anywhere that sets value from outside
because i used to have one game manager for each scene
but now with this ddol i have 2
UI callbacks don't show up as references in VS
well your whole problem is you are acting like each game manager is the same when they are not
So read the thing I sent
im having this problem when crouching , the charactercontroller center goes up as it supposed to but my playerobj stays the same and im not sure how i can pull the playerobj abck up and make the player scale to 0.5 when crouching and back to 2 when not crouching
https://paste.ofcode.org/LgfXbaQRACVUWDfpnmCKd9 , player script