#💻┃code-beginner

1 messages · Page 239 of 1

crimson ibex
#

Vectors are a fundamental mathematical concept which allow you to describe a direction and magnitude
Is the direction stored in C# vector3 object, or is it calculated only in reference to some other Vector3 ?

teal viper
#

Is it raw data? Or does it contain headers? Do you have a link to documentation?

languid spire
#

so if you are interacting with a React Web App why are you not using UnityWebRequest?

potent nymph
#

I suppose it's raw data in a sense

potent nymph
# languid spire so if you are interacting with a React Web App why are you not using UnityWebReq...

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

night mural
languid spire
#

Sorry but if you use UnityWebRequest corretly there is no need to use PersistentData

crimson ibex
#

How can I retrieve it from Vector3 object , via normalized ?

potent nymph
#

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

keen dew
night mural
keen dew
#

if you need it normalized then normalize it

languid spire
potent nymph
#

There is no backend

languid spire
#

you said a React Web App, that is the backend

crimson ibex
#

Hmmm time to go back to school algebra . Thank you @keen dew @night mural @teal viper

potent nymph
#

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

teal viper
potent nymph
#

yes

night mural
potent nymph
#

To send a recorded audio clip to the unity WebGL build

night mural
#

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

teal viper
#

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

potent nymph
#

Yes, I think I looked through all of them

night mural
#

if there's nothing external you shouldn't need to make any requests

teal viper
potent nymph
#

@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

night mural
night mural
potent nymph
#

there are no requests being made, but they do interact with each other

night mural
#

what does that mean

potent nymph
#

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)

wide tapir
#

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

night mural
teal viper
thin hollow
#

is there something like MonoBehaviour.OnApplicationQuit() except when the scene changes?

teal viper
teal viper
teal viper
#

Yeah, that's a solution similar to what I've found as well.

potent nymph
#

I haven't tried downloading a package with nuget before

teal viper
#

Try the solution in the post first.

potent nymph
stuck jay
#

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?

teal viper
#

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.

potent nymph
#

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

teal viper
potent nymph
#

never mind I see the function from the OP

night mural
#

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!

potent nymph
#

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

languid spire
night mural
#

i think that was the original plan? (webgl uses indexedDB to store persistent data)

potent nymph
#

I was looking into that, I'm not sure

night mural
#

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)

languid spire
#

I think a lot will depend on how the React app has wrapped the Unity app

potent nymph
teal viper
#

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.

native seal
#

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?

teal viper
native seal
teal viper
#

Inheritance is an option, but there's also composition and you can combine both too.

native seal
#

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

night mural
native seal
#

alternatively though, I could have an AbilityLogic class which every ability SO has?

#

not sure

night mural
teal viper
#

Yeah, still it depends on the project. 2 arpgs can have a totally different architectures

native seal
#

yes just wondering the most effective way of doing it

night mural
#

the answer is always 'it depends'

cosmic dagger
#

focus on composition and try avoiding an inheritance chain, especially, for BaseClass > Archer > Trapper, etc . . .

native seal
#

or atleast what to avoid

native seal
night mural
#

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

native seal
#

just have the player have a class and subclass?

#

which are two seperate things

static bay
#

If your game is small I see nothing wrong with an inheritance structure. Say the Spire did the same and ended up alright.

teal viper
static bay
#

If you want the ability system to be pretty complex, then ya consider composing them.

native seal
#

yes thats what I planned on doing

#

each class woudl just store a list of abilities

#

and have a name

night mural
#

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)

static bay
#

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.

teal viper
native seal
#

yep okay

native seal
#

but yes everything does effect everything

night mural
#

you don't have to actually 'do ecs' to adopt ideas from the architecture

native seal
#

what does that entail then?

night mural
#

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

static bay
#

Ability systems can be such a rabbit hole I swear.

#

Especially turn based.

cosmic dagger
#

truth . . .

native seal
#

yeah just dont want to go to deep and end up regretting how I did it

#

not turn based though

night mural
#

but that's how you learn

native seal
#

true

night mural
#

it's because an 'ability' isn't really anything and often means 'anything that can happen in the game'

static bay
native seal
#

most likely, anythng you would see in the likes of Diablo, POE, etc

#

or an MMO

#

those types of abilities

night mural
#

oh yeah, ezpz

native seal
#

would using a strategy pattern make sense so the character doesn't have to deal with all the ability logic

night mural
native seal
#

ah okay

night mural
#

compose your abilities out of strategies for the different things an ability must do

native seal
#

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

night mural
#

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

native seal
#

so avoid writing a seperate script for each abilities logic?

#

and generalize them to projectile, melee, DOT, etc

night mural
#

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

native seal
#

im not sure yet

night mural
#

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)

static bay
#

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.

night mural
#

yeah, that's a good setup

native seal
#

hm okay thank you

#

i like that

night mural
#

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

static bay
#

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.

native seal
#

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

static bay
#

Depending on the game scope, ya maybe.

native seal
#

idk yet its my first game

night mural
#

then you should probably just hard code all the abilties 😛

native seal
#

but I do have a lot of ideas

night mural
#

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

native seal
#

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

static bay
native seal
#

ah yea okay

stark girder
#
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?

cosmic dagger
#

the ability system is basically a separate project in itself . . .

native seal
#

well its integral to an arpg

static bay
#

If you want some easy intermediate, do what Slay the Spire did.

native seal
#

thats why im approaching it with caution

static bay
#

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.

native seal
#

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

night mural
native seal
#

what do you mean by triggers?

#

like things that happen when getting hit etc?

night mural
#

'this card does 5 damage. when the target is weak, it does 5 damage again'

native seal
#

ah okay so conditionals

night mural
#

'every time you play a skill, gain 5 block'

static bay
# night mural 😮 i really want to know now though

"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.

static bay
night mural
static bay
#

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.

night mural
#

you see, beginners? just do what works and make your millions

static bay
#

Tbf they had Actions and a proper ActionManager and all that.

#

But their triggers were.... mmm

night mural
#

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

static bay
#

But again, this is pretty robust.

night mural
#

yep that's pretty much what i did in my slay the spire clone

static bay
#

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

polar comet
#

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);

static bay
#

and suddenly you're basically writing your own scripting language

native seal
#

so this is indeed a rabbit hole lol

night mural
#

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 sadtears

static bay
#

and then you just start convulsing

native seal
#

is there documentation for how slay the spire did this?

night mural
#

embrace the blob blobbounce

static bay
night mural
night mural
#

make everything public but control access patterns

#

game state is meant to be queried

#

let it live happily in the light

cosmic dagger
static bay
honest haven
#
    {
        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
night mural
static bay
#

noooooooo

languid spire
polar comet
polar comet
#

ty

cosmic dagger
native seal
night mural
#

hahaha they gave a whole talk on it, hang on

native seal
#

"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. "

night mural
native seal
#

im wathcing that now lol

night mural
#

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

native seal
#

yeah true, but the idea is still the same

night mural
#

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

native seal
#

makes sense

static bay
#

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.

native seal
native seal
#

that i would modify

static bay
# native seal sure, say im using an overlap circle or a collider

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. 
        }
    }
}
night mural
polar comet
#

can I use a float to rotate a gameObject ? I'm to lazy to create a quaternion

night mural
#

but that would just be one piece of the stuff above, where your targeting strategy could factor in the team or not

native seal
#

where would I implement that concept?

#

ive been only thinking in terms of layers

static bay
#

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.

night mural
#

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

native seal
#

so then create multiple " CastSpellAction"'s for each different spell

static bay
#

What're the different spell types you want?

native seal
#

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

static bay
#

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.

night mural
static bay
#

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.

night mural
#

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)

static bay
#

Simply put you just have Actions that spawn entities that do other actions 😛

night mural
#

and you can always have a projectile with 0 travel time

static bay
#

If it's really dynamic, you might have trouble.

night mural
native seal
#

so every target would be evaluating its list of effects to see if they apply

night mural
#

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

native seal
static bay
native seal
#

can you clarify what you mean by Effects?

night mural
#

i tend to call those Auras copying WoW, but some kind of concept for persistent effects which tick is very useful

native seal
#

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

static bay
#

Actions change the game state.

native seal
#

so the actions would have the damage, cooldown, attack speed etc

#

the effects are just how the action applies those

night mural
#

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

burnt vapor
#

Dunno. Does the code actually run? Try placing a debug message at the end of the methods to make sure.

static bay
#

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.

night mural
static bay
#

You will like have shit like DamageEffect and DamageAction.

native seal
#

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?

night mural
#

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

night mural
#

but you could do that at either end really

native seal
#

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

static bay
#

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 😛

night mural
#

i have those too 🤝 gotta resolve dynamic values for stuff out of the gamestate so that you can do damage based on other things!

static bay
#

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.

night mural
#

sounds like you owe me a new FACE

night mural
static bay
#

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.

night mural
#

yepyep

static bay
#

ITS DOOMED

night mural
#

it feels really nice because your features sort of live in independent slices

static bay
#

ya and the definition of what anything "does" can be swapped out

night mural
#

runtime composition is best composition

#

but don't tell the javascript devs

static bay
#
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.

night mural
#

but i understand...somewhere i have a sea of ContextProviders and ContextValueResolvers from long ago

static bay
#

It was kinda cool when it all worked.

#

Maybe I'll dip my toes back into it in the future.

night mural
#

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 ✨

static bay
night mural
#

to be fair this stuff looks worse in code than if you built an inspector to abstract hide away a lot of the ugliness 😄

waxen cypress
#

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

night mural
waxen cypress
#

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

night mural
#

i'm not sure what the xr toolkits include by my understanding is that they are pretty terrible

static bay
#

You'd need to code all that regardless of VR tbf.

night mural
#

well they might include some kind of hand pulling locomotion?>

static bay
#

VR dev isn't thaaaat dfferent other than the Camera being super glued to your head.

waxen cypress
#

ye ik but im still rly new and still trying to understand

#

idk why i picked this stupid idea for my major

night mural
#

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

static bay
#

agreed

hot wave
#

what is a nice namespace for GameInput? UnityChanThink

#

can it be gameinput also?

#

not sure how namespace works

waxen cypress
#

rip

nocturne parcel
#

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...

▶ Play video
loud python
#

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

languid spire
#

I see nowhere in that code that calls SetChestContent on InventoryItemController

loud python
#

I have to assign it manually in play mode

#

in the inspector after it as already instatiated

languid spire
#

so why are you posting code that is irrelevant to your problem? Post the code where you call SetChestContent

loud python
#

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?

languid spire
#

how can I tell you if you don't post the correct code?

loud python
languid spire
#

AI Generated code?

loud python
#

I mean not all of it but some of it

languid spire
#

you know we don't provide help for AI code

loud python
#

why what its helping me learn wtf

languid spire
#

server rules

thorn holly
#

Out of curiosity

languid spire
thorn holly
#

Huh, interesting

dusk dust
#

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?

thorn holly
languid spire
loud python
#

Facts but ive learned more using the AI so whatever helps you learn right

thorn holly
languid spire
thorn holly
#

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

low path
#

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.

languid spire
thorn holly
#

Oof

thorn holly
thorn holly
languid spire
low path
#

That way you are the agent of creation and need to learn from your mistakes.

thorn holly
#

It’s a great way to learn and apply new concepts quickly and make them stick in your brain

faint sluice
#

Is there a function to get a list without specific element in a way it doesn't affect the original list?

low path
#

You can use LINQ’s where() function.

languid spire
#

LinQ, but please don't

gaunt ice
#

you have to deep copy everything

faint sluice
#

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?

faint sluice
languid spire
#

It generate tons of garbage and it has to gate check everything, 90% of what it does is unnecessary overhead

low path
#

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.

gaunt ice
#

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)

languid spire
faint sluice
languid spire
#

List is much less performant than Array

faint sluice
#

I mean with respect to speed atleast

languid spire
#

then he is wrong under most circumstances

faint sluice
#

I might be misremembering too, I'll go recheck

gaunt ice
#

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
magic crown
#

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.

low path
#

You need to get a reference to that game object somehow.

languid spire
#

GameObject.Find, if you really must

low path
#

There are many ways to do that so it depends on circumstances.

magic crown
#

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

languid spire
#

why would it?

#

show code for Blueportal

low path
#

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

magic crown
languid spire
#

and doing it in Update is just wrong

faint sluice
#

My bad

low path
#

both scripts are on the same gameobject so why would you need to inform them of that gameobject?

magic crown
languid spire
languid spire
#

im guessing you are getting an NRE

magic crown
#

nope it unassigned not null since it a public game object

languid spire
#

best show the actual error

faint sluice
magic crown
#

"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"

dusk dust
magic crown
languid spire
#

So your GetComponent<Blueportal>() is failing

#

probably because you are looking on the wrong game object

magic crown
languid spire
#

so why are you looking for it on the same gameobject?

low path
#

"GetComponent" gets the copmonent on the same gameobject

magic crown
#

ooooh yeah did not think about that X) gonna try something else

low path
#

if you call "GetComponent" from "OrangePortal", it will get the component of "BluePortal" on the same gameobject as "OrangePortal"

magic crown
#

completely forgot about that yeah

languid spire
magic crown
#

oh okay sorry

#

i don't usualy ask for help on the discord and just look at the documentation or tutorial

low path
#

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

magic crown
#

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

magic crown
#

will be usefull in the future

queen adder
# languid spire So your GetComponent<Blueportal>() is failing

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

swift crag
#

well, what line is the error on?

#

you need to start with that

languid spire
queen adder
swift crag
#

target.SetActive will cause an error if target is null

languid spire
#

yep, that makes no differene even though it is wrong

swift crag
#

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, [])

queen adder
#

I see, then what method should I use to attach those pieces of code to their respective GameObjects?

swift crag
#

Just make sure that both are assigned in the inspector.

languid spire
#

the inspector

swift crag
#

since these variables are public, they're serialized by Unity by default

queen adder
#

they seem to be in the GameController object

swift crag
#

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

queen adder
#

oh yeah I have 3

swift crag
#

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)

queen adder
#

didn't know that thanks

swift crag
#

You can also do this with your own logs

#
Debug.Log("Oops", this);
queen adder
swift crag
#

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!

queen adder
#

oh that's neat

queen adder
swift crag
languid spire
#

The problem will be that ALL instances of the script will be trying to do the same thing

queen adder
#

nope don't think it is being noticed

languid spire
#

why have this script on more than 1 game object?

queen adder
#

but by all means if that's not best practice I'll make a new file

languid spire
#

I mean if you are checking for specific keyboard input it makes sense to only do that in one specific place

queen adder
#

would anyone here be able to help me with a chunk of code i js cant get right?

languid spire
eternal falconBOT
queen adder
strong laurel
#

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.

queen adder
errant pilot
#

Guys can I send a small 5 sec vid for my problem?

lone ferry
#

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);
    }
}
wintry quarry
#

Also rather than calling Translate twice have you considered combining everything?

Vector3 moveDir = new(moveHorizontal, 0, moveVertical);
transform.Translate(moveDir * speed * Time.deltaTime):```
errant pilot
#

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);

lone ferry
wintry quarry
#

and you are probably using a perspective camera

errant pilot
wintry quarry
#

z not y

shell sorrel
#

just makes sure both vectors in the DrawLine have the same z coord

errant pilot
#

I did both i also changed my camera

errant pilot
#

didint work

wintry quarry
#

you changed your camera in what way

errant pilot
#

i made it orthographic

shell sorrel
#

also where does bottomrightX come from

errant pilot
#

i assign it

wintry quarry
errant pilot
wintry quarry
#

Oh wait

#

what is your game world made of?

shell sorrel
#

its not a z thing since they are vec2

wintry quarry
#

Did you happen to build your game out of UI elements?

#

i.e. is everything happening on a canvas/

shell sorrel
#

yeah could be a overlay canvas

errant pilot
#

a lot not all

wintry quarry
#

your UI is rescaling as you change window sizes

errant pilot
wintry quarry
#

the gizmos are not moving

#

no, UI is for UI

#

gameplay should happen in world space

errant pilot
#

but the problem is the plant i spawn is a child of a UI object

wintry quarry
#

yes that's a problem indeed

#

none of the gameplay stuff should be UI

wintry quarry
#

double check the spelling of your parameter

errant pilot
wintry quarry
#

it makes your objects have consistent world space positions

wintry quarry
#

and then your gizmos (which also have consistent world space positions) will not not appear to "move" when the screen is resized

shell sorrel
#

but otherwise just different workflow

#

can still accomplish what you want, just might have some extra logic for fitting the camera to things

wintry quarry
#

Also all physics, lighting, code etc generally operates with world space coordinates which will now make sense

errant pilot
#

ok and if everything is out of the canvas and i want to rescale my window theyll all like resize?

shell sorrel
#

no reason they could not all be done with sprite renderers and maybe a tilemap

errant pilot
rancid tinsel
#

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?

shell sorrel
#

but are a few ways

wintry quarry
wintry quarry
#

yes, so switch to the Event System stuff

shell sorrel
#

yeah use the EventSystem and its handlers

#

and make sure you have the correct kinda raycaster on your camera for it

shell sorrel
#

once done this will be automatic

rancid tinsel
#

is it just a case of including "using unity.eventsystems" and then changing the OnMouse functions to pointer ones?

slender nymph
#

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

rancid tinsel
shell sorrel
rancid tinsel
#

yes

shell sorrel
#

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

slender nymph
#

that's part of it, yes

shell sorrel
#

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

rancid tinsel
#

i see

#

onmousedown would change to public void OnPointerDown(PointerEventData eventData)?

shell sorrel
#

correct

#

but also needs the corsponding thing up top

rancid tinsel
#

yup

shell sorrel
#

IPointerDownHandler

rancid tinsel
#

got it

#

thank you so much

#

and works like a charm 🙂

shell sorrel
#

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

rancid tinsel
#

yeah that scared me for a second but actually putting the methods in fixed it

shell sorrel
#

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

spiral narwhal
#

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

low path
#

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

spiral narwhal
#

Ahhh yes that would make sense

shell sorrel
#

@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);

hollow forum
#

ive made a movement script but it works even if i take my finger off the movement key

#

any hlep?

wintry quarry
hollow forum
#
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);
    } 
}
wintry quarry
#

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

hollow forum
#

because once i edit it it doesnt stop cause it doesnt update when i take my finger off

#

thanks

odd widget
#

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

timber tide
#

Im lazy so I use lookat

#

you can also run into gimbal issues with Quaternion.Euler though

odd widget
#

🤔

#

i never heard of gimbal

pallid nymph
#

is this for a 2d thing?

odd widget
#

is he the ancient wizard that makes unity?

odd widget
#

i want to make a gun that rotates around the player

timber tide
#

ah, that's fine then since you only need to rotate on one axis

pallid nymph
#

your code seems fine in that case... there's a constant like Mathf.DegToRad btw, I assume that's what you're doing

odd widget
#

oh

#

what's the difference between system Math and unity math?

languid spire
#

system Math uses doubles, unity math uses floats

odd widget
#

aaah

pallid nymph
#

not big, Unity's has a few more things, I guess

odd widget
#

thankyou guys

pallid nymph
#

Unity's actually uses System.Math under the hood, so in a sense it too uses doubles for many things 😄

odd widget
#

unity math is just system Math but with fake mustache and a trenchcoat

pallid nymph
#

exactly

swift crag
#

and some extra operations that are useful for game development

#

e.g. SmoothDamp

pallid nymph
#

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

polar acorn
#

I mean, 0 is positive

pallid nymph
#

Math.Sign return 0 for 0 🤷‍♂️

languid spire
odd widget
#

a light shake

pallid nymph
#

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

torn edge
polar acorn
polar acorn
#

Your Play function searches for a sound and then does nothing with it

torn edge
#

oh word

#

but doesn't s.source.Play() do that

polar acorn
torn edge
#

oh wait

#

this

polar acorn
# torn edge

That wasn't in the code you shared before. Is this AudioManager?

faint sluice
# torn edge

Wait we can add multiple audio sources on same gameobject and have it work perfectly?

polar acorn
#

In this case, since they're stored in a list as they're added, you can properly reference each individual one

torn edge
#

idk why it didnt show up in the file

#

Maybe I didn't save it

polar acorn
torn edge
#

Thanks!

pallid nymph
#

well, at least in the Editor, Unity is returning 1 for Mathf.Sign(-0), so yeah - it's a sad implementation 😛

wintry quarry
#

Sign explicitly says it returns 1 for 0

pallid nymph
#

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

polar acorn
pallid nymph
#

-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 😄

rancid tinsel
#

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

shell sorrel
#

use case heavily depends on how to approach

#

like got static, got singleton's, got SO's everything could reference

verbal dome
#

Component is the base class. But sounds like maybe your problem can be solved in another way

languid spire
rancid tinsel
#

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

shell sorrel
#

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"

rancid tinsel
#

this is what ive thought of but im not sure if it will work

verbal dome
#

Do the tower scripts inherit from the same base class (not counting monobehaviour)?

shell sorrel
verbal dome
#

That could be useful. Or using an interface

rancid tinsel
#

so if i went that route id have to change quite a lot of code

shell sorrel
#

so give them a common base class

#

or make a interface for them

#

that they all implement

verbal dome
rancid tinsel
shell sorrel
#

like TowerBase is a new type

#

then you have a class BallistaScript : TowerBase {

#

and others

verbal dome
shell sorrel
#

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

languid spire
#

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

shell sorrel
#

would also put any common logic in the base since its the stuff you could access without a type cast

rancid tinsel
#

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

shell sorrel
#

and what type would selectedTower be?

#

a GameObject?

rancid tinsel
#

yes

shell sorrel
#

so that could work, but giving them a common base class i fee ls cleaner

rancid tinsel
#

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

shell sorrel
#
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

rancid tinsel
stuck jay
#

Where could I write single variables, like setting a projectile's owner through a GameObject variable?

shell sorrel
#

if (selectedTower.TryGetComponent(out BallistaScript selectedTowerValues)) {

languid spire
shell sorrel
rancid tinsel
summer stump
#

Yes

shell sorrel
#
if (selectedTower.TryGetComponent(out BallistaTower ballistaTower))
{
    // do stuff with ballistaTower if it exists
}
summer stump
#

It CREATES a local selectedTowerValues
To be clear

#

Leave out the type if you want to assign it to a class member variable

shell sorrel
#

in that case would want a new one

#

since it would be a different unrelated type for each case

summer stump
#

Yeah, I didn't see any of the previous stuff. Just wanted to make that clear for any future use.

shell sorrel
#

i still think the common base class is the approach that should be used

languid spire
#

absolutely

shell sorrel
#

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

summer stump
#

Looking back at the conversation, I agree too. It would make things far easier to handle

shell sorrel
rancid tinsel
#

but this seems to work as a workaround

#

thank you

shell sorrel
#

then have both of them extend from it

rancid tinsel
#

im not sure how that would affect the rest of the code I have though as it's probably a mess

shell sorrel
#

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

noble forum
#

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

shell sorrel
#

that is not very hard to code

#

just a wee bit of math, and would best be done per use case

faint sluice
swift crag
#

there will not be a pre-made script that does exactly what you want

timber tide
#

no one gonna hand out code here tbh

noble forum
shell sorrel
#

its just modifying a position based in how many cards you got

#

its just a tiny bit of math

timber tide
#

ugui could probably do most of the work, but I know hearthstone does everything custom

shell sorrel
#

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

timber tide
#

there's one other consideration and it's smushing cards closer if you don't want a proper gap

shell sorrel
#

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

timber tide
#

actually doesn't look like they smush on the board there, but hearthstone does

#

in hand however they probably do

crimson ibex
noble forum
#

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?

thorn iron
#

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

timber tide
#

dont save by the instance ID, either save by asset ID or generate an ID yourself

shell sorrel
#

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

thorn iron
#

I made a ScriptableObject to create a lot of Items faster

timber tide
#

if you don't need to write unique data, but only structure it by SOs, ID lookup to SO is a fine idea

wintry quarry
shell sorrel
#

and Item

wintry quarry
shell sorrel
#

also ontop of those issues, no reason to use the BinaryFormatter

thorn iron
#

oh ok

shell sorrel
#

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

thorn iron
#

how do I say to JSonUtility to Serialize the Item's ID from a dictionary instead of it's InstanceID?

shell sorrel
#

you make it your self

wintry quarry
#

For anything deriving from unityEngine.Object, JsonUtility is going to serialize the instance ID only

languid spire
timber tide
#

make it a field (for the ID), or use AssetPathID

shell sorrel
#

would reference all your SO's in one spot shove them all into a Dictonary by name

wintry quarry
#

use a different serializer, or don't serialize a SO

shell sorrel
#

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

timber tide
#

you don't need to serialize a dictionary anyway, the mapping of ID to Asset should be known on awake

shell sorrel
#

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

reef totem
#

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

thorn iron
#

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, ....)

queen adder
#
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

shell sorrel
#

there is not DontDestroyOnLoad or anything

reef totem
#

no

#

and this script is connected to another game object in the next scene where i want this code to work

shell sorrel
#

with a infinte loop

reef totem
#

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

shell sorrel
gaunt ice
reef totem
#

is that a problem?

shell sorrel
#

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

reef totem
#

what instance

#

the instance of the object

shell sorrel
#

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

shell sorrel
#

which would destroy everything in scene 1 if it was not a addative load

shell sorrel
#

and was it a addative scene load?

#

are both scenes loaded at the same time?

reef totem
reef totem
reef totem
shell sorrel
#

so there is your problem

rocky canyon
#

look it up.. Additive scene loading

shell sorrel
#

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

reef totem
#

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

shell sorrel
#

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

reef totem
#

ok

shell sorrel
#

when you load a scene, everything from the previous scene is gone

#

unless you tell it otherwise

reef totem
#

wait i will look into it put just so i know we are on the same page im going to explain it more thoroughly

rocky canyon
#

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

reef totem
#

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

rocky canyon
#

simplest solution is to stick it in a DontDestroyOnLoad(); as mentioned above

shell sorrel
#

these are 2 different scenes

reef totem
#

i did not know that existed

rocky canyon
#

you'd always have access to it

shell sorrel
#

its not the same object

reef totem
#

likewise to void start or void awake

shell sorrel
#

no you mark a whole gamboject with it

#

and that object will survive scene loads

rocky canyon
languid spire
shell sorrel
#

there is nothing to prevent you from getting more then one

reef totem
#

can you show me how

rocky canyon
#

DontDestroyOnLoad(this);

reef totem
#

so dont destroy on start is not a function

rocky canyon
#

u can put it in start or awke

shell sorrel
rocky canyon
#

would that not encompass the gameobject too?

#

this.gameObject then

shell sorrel
rocky canyon
#

or gameObject

rocky canyon
#

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

reef totem
#

i get it

rocky canyon
#

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

shell sorrel
#

since its signature is UnityEngine.Object

rocky canyon
#

i think it does.. b/c i didnt notice it

reef totem
#

does not work

rocky canyon
#

and i have a few DDOL

shell sorrel
#

but it applies to ta GO not a component

rocky canyon
#

whats setforce?

shell sorrel
rocky canyon
#

u want the script/ gameobject

languid spire
rocky canyon
#

so all ur code sticks around

#

its not meant for variables like float or vectors

reef totem
#

sorry about asking these sillly questions

#

im a very big begginer

rocky canyon
#

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

rocky canyon
#

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

reef totem
#

i swear i think i have autism

rocky canyon
#
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

polar acorn
#

Is it the object this script is on

rocky canyon
#

its weird to call it from another script

#

in my opinion

reef totem
#

game manager has more than one script

rocky canyon
#

every script attached to that object will be not destroyed

reef totem
#

the the object game manager has more than one script in this case

rocky canyon
#

u may want to rethink ur setup.. and have only certain scripts on that gameobject

polar acorn
#

The whole object will be a DDOL

reef totem
#

i think i will call it in the script game manager later on but for now i just want this to work

pallid nymph
#

(I'll just insert my standard "DDOLs suck btw" comment 😅 )

reef totem
#

what is ddol

slender nymph
#

DontDestroyOnLoad

polar acorn
pallid nymph
shell sorrel
#

tend to have a init scene with all the important stuff i want to keep a around

#

then that will do addative loads

rocky canyon
#

additive scene loading is gonna be more confusing to him than ddol

shell sorrel
#

i am not suggesting somoene new does addative loads

queen adder
#

I think I need an off toggle?

shell sorrel
polar acorn
#

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

shell sorrel
#

there is not reason for it to have the while loop

queen adder
#

let me try sans loop

rocky canyon
pallid nymph
shell sorrel
rocky canyon
#

i havent gotten that involved yet. but its possible 😄

shell sorrel
#

for both technical and workflow reasons

polar acorn
reef totem
#

update nothong works my player is not moving

shell sorrel
#

find it so amusing how you guys need a acrynom for a regular object

rocky canyon
#

WUTAW

#

what u talkin about willis

reef totem
#

the variable setforce is 0

#

even when a new scene loads

rocky canyon
#

is it 0 before u press play?

reef totem
#

no

#

because it set it in the settigns menu to be 2000

#

and then i load the next scene and its 0

polar acorn
#

Share the updated code

reef totem
#

wait i have so many screenshots i dont know wich one is wich

#

sorry

polar acorn
#

Instead of sending screenshots, send !code

eternal falconBOT
reef totem
#

ok i got it

#

its fine i already sent it

slender nymph
#

!screenshots

eternal falconBOT
#

mad No

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

polar acorn
reef totem
polar acorn
faint sluice
rich adder
#

did not do it

polar acorn
#

Actually this screenshot also didn't do the first part either

#

Run the game

polar acorn
#

Load the second scene

#

then search

reef totem
#

how do i search

shell sorrel
#

while in playmode

polar acorn
reef totem
#

i will just send a ss with my game running

rich adder
polar acorn
austere tendon
#

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.

reef totem
polar acorn
# reef totem

Okay now this screenshot but with the search in the box like I asked

shell sorrel
austere tendon
reef totem
polar acorn
#

Why are there two

reef totem
#

idk i probably put 2 by accidnt

polar acorn
#

then see

reef totem
#

i removed that one

faint sluice
shell sorrel
polar acorn
shell sorrel
#

the problem is they unload the whole object and reload it and expect it to be teh same

reef totem
#

still dont work

faint sluice
polar acorn
#

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

polar acorn
shell sorrel
#

well 2 coppies of it there

polar acorn
#

As I said

shell sorrel
#

which means it existed in more then 1 scene

polar acorn
#

There's two copies of it.

#

One has 2000, one has 0

#

You want there to be one instance of this. Ever.

reef totem
#

so the ddol makes it so i only need one game manager

faint sluice
polar acorn
reef totem
#

because i used to have one game manager for each scene

#

but now with this ddol i have 2

polar acorn
shell sorrel
polar acorn
cinder crag