#💻┃code-beginner

1 messages · Page 259 of 1

queen adder
#

not gameobject actually, a text

rich adder
#

why is Text not a prefab

#

components need to live on a gameobject

queen adder
#

the text that pops, instead of moving this again and again i want this to be cloned every time a player clicks the piece

rich adder
#

yeah just make a prefab out of it and Instantiate it

queen adder
#

instantiate where in a script?

rich adder
#

instead of doing this
TextPop textPop = FindObjectOfType<TextPop>();
MoneyManager moneyManager = FindObjectOfType<MoneyManager>();

#

TextPop textPop = Instantiate(etc.

queen adder
#

yes, but now wait

#

because

#

the piece where this script you mentioned is

#

is a prefab and is instantiated from another script PieceSpawner

rich adder
#

thats not the TextObject ?

queen adder
#

and it will be impossible to just say public text textpop cause i cant asign the text to it since its a prefab

rich adder
#

you would need to make a custom utility app yourself

queen adder
#

idk how to describe it

rich adder
#

if the textobject is already a prefab it should have no problem being added into another prefab

queen adder
#

oh okay didnt know that let me try

rich adder
#

only thing wont work is Prefab -> SceneObject

swift crag
#

the rule is that assets can't reference scene objects

#

(and scene objects can't reference objects in other scenes)

rich adder
#

cause they're actual assets and they live in the Project folder (unlike gameobjects in the scene which are data inside a YAML of Scene asset file)

swift crag
#

well, the prefabs are also just a blob of YAML :p

#

sometimes I open asset files to manually edit them

rich adder
#

true true never opened prefabs, had a feeling they would be

rich adder
#

Unity used to have this thing already built in but removed it

queen adder
#

it highlights red now

#

the pop function

rich adder
#

because ur spawning it as Text not as whatever the script that contains Pop method is

#

computer has no idea what Pop inside Text is

queen adder
#

ohh right

#

like this

swift crag
#

You should just reference it as a TextPop directly.

rich adder
#

lol thats backwards

swift crag
#

give TextPop a field that references its Text component

#

then you can easily do...

#
var instance = Instantiate(prefab);
instance.text.text = "whatever";
instance.Pop(screenPosition);
queen adder
#

what is a var?

swift crag
#

var is a keyword that lets you omit a type name when creating a variable.

swift crag
#
TextPop instance = Instantiate(prefab);
#

This will have the same outcome.

#

(and make it more obvious what instance is here, since prefab isn't a great name)

queen adder
#

so wait first i did
public Text popText;
then
var clonedPopText = Instantiate(popText);


clonedPopText.GetComponent<TextPop>().Pop(screenPosition);```
queen adder
#

idk, how to do this then

rich adder
#

store the Text inside TextPop

#

then

[SerializeField] private TextPop textPopPrefab ;
#

var textPopInstance = Instantiate(textPopPrefab, etc..

#
textPopInstance .textField.text = "something"
textPopInstance.Pop(etc..```
#

ofc make sure you have a field inside TextPop for public Text textField and assigned

queen adder
#

and what is textField?

#

i dont wanna change the text just yet

rich adder
queen adder
#

i think i dont understand something

#

oh okay i see it

swift crag
rich adder
#

we both sent you examples of same thing , none had .Instantiate lol

queen adder
rich adder
queen adder
#

idk i understood it like that 😭

swift crag
#

store the Text inside TextPop

rich adder
#

doing a useless GetComponent<TextPop>()

#

when you can just store it as TextPop

queen adder
#

ohhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh

#

sure

#

but then i would have to make two variables? one for textpop script and another for text object i want to position

rich adder
#

TextPop is the whole object no? you're positioning the same thing

#

they're both the same transform gameObject

queen adder
#

but doing var clonedTextPop = Instantiate(popText); is just like instantiating a script

swift crag
#

Instantiating a component instantiates the entire game object it's attached to.

rich adder
#

you're cloning the prefab

queen adder
#

oh well then

rich adder
#

which is a template to a gameobject

swift crag
#

Components can never exist by themselves

#

that's why new TextPop() doesn't work

queen adder
#

whats this now?

rich adder
queen adder
#

oh okay haha

rich adder
#

the view/layout got lost somewhere

queen adder
#

another one

#
{
    rectTransform.position = screenPos;
}```
rich adder
#

well is rectTransform assigned

queen adder
#

i think so

rich adder
#

is this inside TextPop?

swift crag
#

Start runs the frame after instantiation.

queen adder
#

yes

swift crag
#

It's too late.

rich adder
#

why do you have another field called textPop inside TextPop

swift crag
#

and yes, why do you have it referencing another TextPop..?

queen adder
#

oh i just forgot to remove this from my previous mistakes

swift crag
#

stop and read what's been suggested again

rich adder
swift crag
#

you don't even need that

#

transform.position is all you need

rich adder
#

true you're not even using anchored pos

swift crag
#

there's nothing special about setting .position on a RectTransform vs. on the same thing referenced as a Transform

queen adder
#

the poptext is now cloning but not really showing in game

rich adder
#

yeah cause you need to reference the Canvas and spawn them inside of it as child

#

text wont show outside a canvas

queen adder
#

ohhhhhhhhhhhhh well

rich adder
#

var clonedTextPop = Instantiate(popText, canvasReference);

#

ohh you have an issue though where you need to Get this canvas now like the money script, because you put instantiate inside the falling object which is prefab (cannot assign field in inspector for Canvas)

queen adder
#

oh yeah

#

let me go take a shower ill be right back

south sky
#

Yo @rich adder sorry bro u gotta teach a lil bit more bc I still didnt get what you meant by your previous answer to me. I just want to know how to get the coordinate position of a gameobject thats inside a prefab. For example. The gameobject room1 B is placed in a position on the prefab and when the prefab is instantiated I want to be able to get that coordinate position and use it within another script. Still learning so sorry for wasting ur time

rich adder
#

then access them when you spawn as that

south sky
#

You are an angel in disguise

#

Preciate it man

rich adder
covert sinew
#

Is there a good method for making something move towards a target vector, but with slippery momentum? (I.E, it overshoots slightly, and slides around with momentum)

I've got LeanTween, but that doesn't allow for continuous movement, only looping animations with set lengths.

queen adder
#

nvm im back

queen adder
rancid tinsel
#

when I load to a different scene and back to the one where the DDOL singleton is in, I end up with 2 of the same singleton - any idea what I might be doing wrong?

covert sinew
#

I want my UI elements to move towards my mouse, but in a slippery way.

#

Or other locations

south sky
queen adder
rich adder
swift crag
rich adder
swift crag
#

Second order dynamics let you "follow" a target value in a way that has momentum.

rancid tinsel
swift crag
#

Destroy(this) won't destroy the game object

#

That may be what you're seeing.

rancid tinsel
#

ohhh

swift crag
#

a destroyed SceneManagerScript, but duplicate game objects

#

that sentence is a mess

#

you have destroyed the SceneManagerScript, but you still have a duplicate game object

#

there we go

rancid tinsel
#

so instead of "this" do gameObject?

rich adder
#

sure

swift crag
#

yes, that will destroy the entire object

queen adder
#

is there anyone that did spriterenderer rule tile before?

#

basically a ruletile but for gameobjects

covert sinew
queen adder
swift crag
rich adder
swift crag
#

Add a SecondOrderDynamicsFloat or SecondOrderDynamicsVector3 field to a class. Call Setup() on it once, then call Update() on it every frame. Pass it Time.deltaTime for the t argument and the target value for the x argument.

#

The three parameters -- f, z, and r -- are described in the video.

#

I should set up a little visualizer like he has in the video.

queen adder
dawn kestrel
#

sorry for the out of nowhere reply. Turns out you just need to multiply the quartenion by the vector3 (in that order) and the output will be what I was looking for.

covert sinew
rich adder
#

alternative is to do this properly by spawning these sprites from a scene object so you can plug the references directly

queen adder
#

alr thanks you so much

swift crag
swift crag
queen adder
rich adder
#

think i forgot that in my example, that myb lol

covert sinew
swift crag
#

i can't do a lot for you if you just say "I understand none of this"

queen adder
#

seems like it works 🙂

swift crag
swift crag
covert sinew
#

Yeah, I've used those in the past.

rich adder
covert sinew
rich adder
#

btw Destroy has a float variable for time till destroy

queen adder
#

i just didnt set up animation and destroy function

swift crag
covert sinew
#

then it looks like I'm using yours, 🤡 My tiny, weak brain thanks you.

swift crag
#

it's used to make the Q and E buttons bounce in this video

queen adder
#

why is that animator controller empty and i cannot add an animation to it?

ionic zephyr
#

is tehre a problem if I call a Method in Update?

rich adder
rich adder
ionic zephyr
#

basically I am registering the direction vector from an InputManager and passing it onto the character movement script every frame

rich adder
#

should be fine

swift crag
queen adder
swift crag
#

Do whatever you want in Update.

rich adder
#

I was thinking you had like GetComponent or FindObject which is kinda heavy to do every frame

swift crag
#

even those are very very fast

#

those are bad because they give you brittle code

#

they're still slower than the better alternatives, of course

rich adder
#

hmm maybe i was thinking GameObject.Find

queen adder
swift crag
#

you can do it many times per frame and your game won't blow up

rich adder
#

oh yeah for sure wont blow up just bad habit no?

swift crag
#

it's bad because it makes your game fall over and explode when you fix a typo in something's name

rich adder
#

oh always thought it used reflection / scanned all scene objects thats slow

queen adder
wicked stratus
#

If I were to write,

//then 
jsonUtility.fromJson<BotObjectSerializable>(aBotObjectSerializableJSON)

would it be able to handle the list<int> s inside the class?

swift crag
rich adder
swift crag
#

But computers are still fast.

#

I'm just pointing out that calling Find a couple dozen times per frame isn't going to tank your framerate

#

it's not some massively evil bugbear

wicked stratus
#

I struggle to know what JsonUtility can handle

wicked stratus
#

but it can't handle dictionaries, right?

swift crag
#

Rule of thumb: If it serializes in the inspector, it should serialize in JsonUtility (with some exceptions, I guess)

#

you can't serialize a single float, for example

swift crag
wicked stratus
rich adder
wicked stratus
swift crag
#

(even though that's valid JSON)

#

most people think of JSON as being at least an object or an array

#

but it can absolutely just be a number or a string

wicked stratus
#

that's very helpful to know

wicked stratus
rich adder
wicked stratus
#

it was awhile ago

rich adder
#

Def give it a try again from package manager at some point, its a solid plugin

swift crag
#

that's how I've installed it

#

and it's very useful

rich adder
#

the only thing it doesn't like is Vector3 but there is a workaround

wicked stratus
#

I'm already kind of used to JSON Utility- what are the differences?

swift crag
#

You can use it roughly the same way

#

JsonConvert.SerializeObject(whatever)

rich adder
swift crag
#

It's extremely extensible. I use a custom converter to serialize objects by a GUID, and to then look them up by GUID when deserializing

wicked stratus
#

that would make things way nicer. does it work with custom classes

swift crag
#

Note that dictionaries are still a bit limited out of the box.

rich adder
#

works with classes / struct you name it

swift crag
#

The keys need to be strings.

#

(since that's how JSON works)

rich adder
#

wdym

#

could've sowrne used dictionaries with json.net without having string as key

swift crag
#

JSON object names are strings.

timber tide
#

I think I was having problems with serializing dictionaries, but im so used to just breaking everything down into lists and reconstructing the dictionaries anyway (at startup)

swift crag
#

They can't be an arbitrary JSON value (like the value is)

rich adder
#

Oh like it stores as string you mean

swift crag
#

Yes.

rich adder
#

yea

#

got confused for a seclol

swift crag
#

I guess it can handle turning that string back into a few other types, like integers

#

I forget

rich adder
#

so Deserialize doing all the magic

timber tide
#

ive been just sticking to utility lately just because it's like the right amount of serialization I need

#

and more that it lines up with what I can serialize in the editor anyway

swift crag
#

i briefly played with writing a custom converter for dictionaries

#
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JObject obj = JObject.Load(reader);
        IDictionary<K, V> dict = (IDictionary<K, V>) existingValue ?? new Dictionary<K, V>();

        foreach (var prop in obj.Properties())
        {
            IdentifiableRegistry.TryGet(typeof(K), new Guid(prop.Name), out var result);
            dict[result as K] = (V) prop.Value.ToObject(typeof(V));
        }

        return dict;
    }
#

i don't enjoy reading this code

#

I just wound up serializing lots of pairs of keys and values anyway

eternal needle
#

🤔 should work out of the box with Newtonsoft.

swift crag
#

(that's my own Guid class, not System.Guid)

swift crag
#

not just a string

#

notably, in this case, I was serializing a dictionary whose keys were scriptable objects

rich adder
#

json.net has a hard time anything unity tbh

#

vector3 gives it a self-intersecting loop issue

swift crag
eternal needle
rich adder
#

I use custom struct for V3 though because the one on Unity cloud has json.net without that option so you get same error during serialization

queen adder
#

after i reopened unity this magically stoped working

{
    MoneyManager moneyManager = FindObjectOfType<MoneyManager>();

    if (moneyManager != null)
    {
        moneyManager.AddMoney(5);
    }

    Canvas textPopCanvas = FindObjectOfType<Canvas>();
    if(textPopCanvas.tag == "TextPopCanvas")
    {

        Vector2 screenPosition = Camera.main.WorldToScreenPoint(transform.position);

        var clonedTextPop = Instantiate(popText, textPopCanvas.transform);

        clonedTextPop.Pop(screenPosition);

        Destroy(gameObject);
    }  
}

its giving me money but not destroying the object or popping the text

swift crag
#

If you have more than one Canvas in your scene, the exact object found by FindObjectOfType will depend on the order the canvases were created it

#

which can vary after a restart

#

consider just finding an object by tag and then getting a Canvas from it

rich adder
#

could also make a script TextCanvas placed on that canvas, and find that

wicked stratus
swift crag
#

No, because Unity can't serialize a list of lists

#

You have to create a bit of indirection

#

List<MyStruct> where MyStruct contains a List<int>

#

This is a situation where Json.NET is strictly better

wicked stratus
queen adder
#

damnnn it works

#

and it looks AMAZING

swift crag
wicked stratus
rich adder
ionic zephyr
#

How can I adjust the gravity of my game, because I have this problem: ¿why in one project objects fall slow and in other fall faster?

#

Both have the same rigidbody stats

swift crag
#

that's probably down to the scale of your game

#

if everything is large and the camera is zoomed out, things will appear to fall slowly

ionic zephyr
queen adder
ionic zephyr
#

it is the default camera

#

so why does in one project fall fast and in other slow?

queen adder
#

why its red? first time using switch

frigid root
#

Does it give you any hints when you hover over the red squiggle with your mouse?

queen adder
frigid root
#

I'm not sure if Visual Studio highlights it as an error, but you might need to put break

#

Yep : )

cosmic dagger
queen adder
#

huh what?

ionic zephyr
#

why with Unity new inputsystem my object falls slow with rigidbody?

cosmic dagger
queen adder
frigid root
# queen adder

Unity won't know what you mean by "LeftShift".press() because "LeftShift" is just a string. You could try Input.GetKey(KeyCode.LeftShift) instead to check whether or not the left shift key is being pressed.

cosmic dagger
queen adder
#

ah, i used a string extension

#


public void Pop(Vector2 screenPos, int value)
{
    transform.position = screenPos;
    if (value > 0)
    {
        textComponent.text = "$" + value.ToString();

    } else
    {
        value = -value;
        textComponent.text = "-$"+ value.ToString();
    }
    
}```
it gives me NullReferenceException, did i do something wrong when trying to get text component?
cosmic dagger
cosmic dagger
queen adder
#

NullReferenceException: Object reference not set to an instance of an object
TextPop.Pop (UnityEngine.Vector2 screenPos, System.Int32 value) (at Assets/Scripts/TextPop.cs:16)
PieceManager.OnMouseDown () (at Assets/Scripts/PieceManager.cs:55)
UnityEngine.SendMouseEvents:DoSendMouseEvents(Int32)

queen adder
#

textComponent.text = "$" + value.ToString();

cosmic dagger
queen adder
#

no

ionic zephyr
#

why when i put a custom Vector2 in rigidbody2D my object falls slow?

rancid tinsel
#

how do you change the volume of an audio source? ive tried audioSource.volume but that doesn't seem to do anything

polar acorn
cosmic dagger
# queen adder no

i would start with that. it's very important to know what a reference type and a value type are . . .

ionic zephyr
queen adder
#

alr but how to fix it

cosmic dagger
wicked stratus
#

ah, nvm

polar acorn
cosmic dagger
timid quartz
#

Say I have a script (UIController) and a different script that inherits from it (MainMenu : UIController) and I have a serialized field within UIController that I do NOT want to appear in the inspector for Main Menu. Is there a way to make that happen?

polar acorn
#

Keep it what it is

rancid tinsel
cosmic dagger
#

@queen adder there are only two variables on that line. can you at least tell what the two variables are?

rancid tinsel
ionic zephyr
frigid sequoia
#

Guys I have this thingy where it is a model with a shape key where the sides are pushed away between then, mantaining their shape. This is so I can make several of these with variable sizes with ease when importing them. I want then to be a single entity cause I want them to behave entirely like one (like be isntantiated togheter, share health and stuff). But I am actually wondering for a while... How can I make so the colliders fit any possible distance this shape may have? Cause I need the middle one to be a different type of collider than the other two.... Could I calculate something about that with code or should I try something different entirely?

polar acorn
ionic zephyr
rancid tinsel
queen adder
#

where in unity docs did they tell that KeyCode.LeftShift is "left shift"

polar acorn
rancid tinsel
cosmic dagger
ionic zephyr
polar acorn
cosmic dagger
queen adder
polar acorn
ionic zephyr
#

but I cant modify it

cosmic dagger
rancid tinsel
#

i just realised what it is

#

i changed the method name which means its missing from the volume slider

polar acorn
wicked stratus
#

or do i need to unpack

swift crag
#

but you can always try it and see (:

covert sinew
swift crag
#

you set it up once, then update it constantly

#

the Position property gives you the current value

#

If you know your velocity, you can also pass it as a third argument to Update. If you don't, it'll just calculate a velocity based on how much x has changed since the last update

covert sinew
swift crag
#

The video describes how those three parameters work

#

Roughly speaking, f is the frequency of oscillation, z is the damping, and r is how much it “winds up” before moving to the target

slate mason
#

Hello, I'm trying to make an online multiplayer platformer game, just doing the basics as of now. I have a player, and a moving platform. I want the player to move with the platform while standing on it. I tried making the platform the player's parent, but the player doesn't move with the platform still. (the player stays in the same place but it's local coordinates change, indicating that it's moving relative to it's parent.) How should I be doing this?

nocturne parcel
#

Show script. We can't just guess what's wrong.

minor patio
#

so I've got a method on a button that is returning an object twice for some unknown reason - debugger (I dunno if I'm watching the right things even) just confirms that once the method has run it returns to the start of the method (or at least the break-point I created). Debug log returns everything as in proper working order except for the returning object, which gets two rank increases instead of one. Code not shown because I can't figure out the Pastebin quicklink...

#

how does one find the Pastebin/Hastebin quicklinks?

viral hemlock
#

does any one know why my random range is only returning 1?

 private float Spread()
 {
     int random = Random.Range(1, 2);
     if (random == 1 && _playerMovementScript._isWalking == true) /*return +_bulletSpreadWalk*/ Debug.Log("1w");
     if (random == 2 && _playerMovementScript._isWalking == true) /*return -_bulletSpreadWalk;*/ Debug.Log("2w");
     if (random == 1 && _playerMovementScript._isSprinting == true) /*return +_bulletSpreadSprint*/ Debug.Log("1S");
     if (random == 2 && _playerMovementScript._isSprinting == true) /*return -_bulletSpreadSprint*/ Debug.Log("2S");

     return 0;
 }```
eternal falconBOT
minor patio
#

I just found it thanks

nocturne parcel
#

You are essentially saying "give me a number between 1 and 1"

#

wait, no

#

It should still give a float?

viral hemlock
minor patio
nocturne parcel
cosmic dagger
nocturne parcel
#

Oh then I was right

frigid root
nocturne parcel
#

The max should be 3

cosmic dagger
nocturne parcel
#

Either way, if you want a 50/50 chance, I'd go with floats and (0f, 1f) honestly

viral hemlock
#

thank you everyone

#

the problem was with the max value

slate mason
nocturne parcel
#

And what is the problem again?

eternal falconBOT
slate mason
#

The platform becomes the parent of the player correctly, but when the platform moves, the player doesn't move with it

nocturne parcel
#

You're setting the player to be the parent of the platform, no?

slate mason
#

No I'm setting the platform to be the parent, so that the player becomes the child and moves with the platform

nocturne parcel
#

Ah, I see.

#

Could you try using SetParent?

#

If I'm not mistaken, SetParent (with false as second parameter) would force the child to move next to the parent

thorn holly
slate mason
#

I tried just now, but when the player landed on the platform it teleported far away

covert sinew
#

@swift crag I've finally gotten it working, and the sheer relief and excitement I feel is palpable. Thank you so much for your help and code. It looks so great!

#

I really can't thank you enough

slate mason
nocturne parcel
thorn holly
summer stump
nocturne parcel
slate mason
#

I just tried SetParent with the parameter set to true, and it's back to how it was. But I'm noticing there is like a very subtle movement but it's a bit jittery, but it's moving only a few pixels

summer stump
#

This is a dynamic rigidbody, right?

slate mason
slate mason
summer stump
summer stump
slate mason
#

Yes the player has a rigidbody that is not kinematic (if that is what you are asking)

summer stump
#

If so, its position is not gonna move with the platform properly

#

Yeah, that is what I'm asking. Non-kinematic means dynamic

slate mason
#

so when the player is on the platform I should change it's rigidbody to kinematic?

summer stump
slate mason
#

So making the player's rigidbody kinematic when it's on the platform works! but now I can't move the player 😄 maybe I should change the player controls and not use velocity overall?

minor patio
#

ugh, this is doing my head in
I'm claiming a mental health day...

thorn holly
scarlet skiff
#

i have a prefab that has a script component but sometimes i wanna spawn in a version of this prefab wothout that specific component is there a way to do that?

currently i tried this and it doesnt seem to work

minor patio
#

is there even a thing?

swift crag
scarlet skiff
# swift crag Destroying the component should work fine. What goes wrong?

hmm i was afraid that the problem was going to be something else, but i expected that.

well you see, what decides if a projectile can be parried or not, is this script: https://gdl.space/jenivasexi.cpp

And once it decides that, it gets painted red, thats how the player knows they can parry.
Problem with the bomb projectile, is that it can split into 2 smaller bombs, but for some reason, whether they are parryable or not (red or not) is ALWAYS dependant if the bomb they "split" from is parryable or not. but i dont want smaller bombs to be parryable, ever.

I assume this code of the parryable script should not be like this, maybe this changed something that shouldnt be changed

swift crag
#

Destruction isn't instant.

#

It happens at the end of the frame, iirc

#

or maybe on the next frame?

#

It sounds like that Start method is executing before the component dies.

#

Verify that with a log

#

log both in Start and in OnDestroy (add that method)

scarlet skiff
#

ye i thoguht abt that, but then why does it always depend on the "main" bomb? its a random nuimber generator that decodes if its gonna be parryable or not

#

but never seen a smaller bomb be parryable when the main one wise, vice verca

swift crag
scarlet skiff
swift crag
#

one thing -- make bombPrefab a Bomb, not a GameObject; that'll simplify your code

#

it'll avoid the GetComponent calls

swift crag
summer stump
scarlet skiff
swift crag
scarlet skiff
#

after bomb split

#

why did the initiation of the original bomb not debug.log("start") ?

#

weird

rancid tinsel
#

I have an issue where if an enemy leaves the tower's targetingRange before it fires a shot, it changes to the next enemy in the array, often not able to hit that enemy before they leave the targetingRange - causing the tower to be basically stunlocked and not doing anything. What could I change in this code to fix that? https://gdl.space/qotomiqiki.cs

swift crag
#

the first bomb's Parryable logs start and destroy

#

the small bombs both log destroy

swift crag
rancid tinsel
hollow slate
#

if you're talking about an enemy moving out of the range making the projectile target the next target in range:

You should tell the individual projectile to target whatever you shot at, don't let the tower give that information.

#

also, JESUS, use vectors instead of four cases for each direction hahah

rancid tinsel
hollow slate
#

Can you be more specific with the issue?

#

From what I understand, it breaks when a character that you shot at walks out of the targeting range after you've shot.

#

I don't see why this breaks it though...

rancid tinsel
#

I think the issue is with the else {target = null} as its causing it to essentially reset the shot?

#

so it doesn't complete the shot on the tower that left its range

#

and then it starts a new shot on the next tower thats in range

hollow slate
#

right, I can see it.

#

uhh, so currently the tower handles the shooting and the projectile itself right?

rancid tinsel
#

yes, if the projectile loses its target (if target was destroyed) it just keeps moving in the direction it was fired in

#

the issue seems to be with the towers themselves

hollow slate
#

right, okay. So the tower just shoots the last bullet that then travel in the general direction of where the enemy left the range?
After this the tower just gives up?

rancid tinsel
#

it essentially gives up if enemies leave its range before its finished its shot

hollow slate
#

finished its shot? Meaning finished charging it up, or just when it hits an enemy?

rancid tinsel
#

charging it up

hollow slate
#

ahh, okay

#

where's the code for the charging up?

rancid tinsel
#

line 137 onwards I believe

#

so this bit

#

maybe this?

hollow slate
#

well, FindTarget() should take care of it no?

#

it's not like the amount of targets are empty right?

rancid tinsel
#

FindTargetAerial and FindTarget check different sorting layers I believe

#

different towers can target different sorting layers

#

layermask* i meann

hollow slate
#

ah, makes sense.
In this case it does find more targets though right?

#

set your inspector to debug mode and you can see what the current target is.

rancid tinsel
#

it should yes, but i feel like this will just do the same thing it was doing earlier

hollow slate
#

yeah. If it doesn't have a target at all, that behaviour would make sense right?

#

if it does have a target, we know that's not the issue

#

then it's something about getting stuck in the charging process.

#

right-click the inspector window

#

and select Debug

#

to see private variables

#

check if the target is null when the tower is wonky

hushed hare
#

Anyone know any good torurials

polar acorn
eternal falconBOT
#

:teacher: Unity Learn ↗

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

potent nymph
#

do I share code on hastebin or pastebin, I forgot which one is the bootleg

#

nvm looks like pastebin has better reviews, so it looks like the right one

summer stump
shell sorrel
#

gdl.space i like how spartan it is

#

only what you need with good colors out of the box nothing extra

potent nymph
#

ah, thanks

#

the problem is that is has a constructor, and I'm unsure how to split my code when it has a constructor

#

(I'd like to move the CreateVertexBufferCS method to a different class for example)

shell sorrel
#

you can chain constructors

timber tide
#

2 constructor

summer stump
#

On a quick look, that is all a single purpose, and is quite short
Where do you want it split? oh, missed the last sentence, nm

shell sorrel
#

but also think i would just use composition

potent nymph
#

haven't heard of composition before, I'll look into that

shell sorrel
#

like you mention a method

#

do you want all data it touches moved as well?

#

if not i would just leave it

potent nymph
#

not necessarily moved, but just accessible from the child class

kindred stratus
#

im having a issue with this movement script ```public class Movement : MonoBehaviour
{

public float speed;

void Update()
{

if (Input.GetKey(KeyCode.D))
    {
    transform.Translate(Vector2.right * speed);
    }

else if (Input.GetKey(KeyCode.A))
    {
    transform.Translate(Vector2.left * speed);
    }

else if (Input.GetKey(KeyCode.S))
    {
    transform.Translate(Vector2.down * speed);
    }

else if (Input.GetKey(KeyCode.W))
    {
    transform.Translate(Vector2.up * speed);
    }
}

}``` im having a issue where if my framerate goes down a decent bit the movement looks really choppy and not smooth at all is there any way to fix it

timber tide
#

why cant the child access it

timber tide
potent nymph
summer stump
shell sorrel
#

public NewMeshData(args) : base(args) {

potent nymph
#

it's gonna get really long, I'm in the middle of refactoring something actually

#

I just shortened it down for the example

shell sorrel
#

74 lines is not long

#

but ok

timber tide
#

overriding constructor or making another new one in the child, no?

potent nymph
shell sorrel
#

i would never split things due to the size of the code, only for splitting the functinality

potent nymph
#

probably more, since I have to include the fallback for devices that don't support compute shaders

shell sorrel
#

but also you can just define a new constructor on the extending class

#

it just has to call the previous one via the syntax i showed above

#

or just put the stuff in its own class, and make that a member of the main class

queen adder
#
 
 
if (Holding)
        {
            TargetDirection = TargetPoint.position - Grabbed.position;

            Grabbed.transform.GetComponent<Rigidbody>().AddForce(TargetDirection * 2f, ForceMode.Acceleration);



        }

How do I get the grabbed object to get exactly to the target point.

silk night
hollow slate
#

there's plenty of tutorials for movement in 2D, I'd recommend watching one or two!

queen adder
silk night
#

Well you can make it have velocity in the direciton of the target point and slow the velocity based on distance

shell sorrel
#

it can still effect other things if you use MovePosition on the rigidbody

#

but otherwise i would directly take control over velocity

#

so i can slow it down as it approaches

hollow slate
#

physics based grabbing is quite difficult to implement, but you're on the right track here. Things like dampening though is quite a pain in the ass to code.

#

I'd suggest creating a joint between the object you want to grab and the grabbing-point. This way you let Unity handle the physics themselves after some tweaking.

#

things like rotation can also be handled with a "character joint", but it requires a lot of fiddling to get correct behaviour (speaking from experience with the damn thing)

teal viper
scarlet skiff
#

But where to go from there? If it still somehow colours them

worldly widget
silk night
# worldly widget

Make the parent abstract, declare an abstract function "OnCustomTrigger(AIStats stats)" or whatever you want to name it and call that
In the child you then define the function

shell sorrel
#

save it to a field, or just make it a function you call in to get it

covert sinew
#

https://pastebin.com/z8M9tVSj

https://pastebin.com/mfHKzK4t

I need help!

At line 291 of the first paste, an Empty Slot is being added to a Grid Layout Group, and then, an inventory icon is spawned, and that empty slot is set as a target for a smooth transition function.

When I use this normally, it works fine, but when I try to insert an empty into the grid layout, and set its Child Index to the correct number, it doesn't work correctly, the icon on the far end seeming to snap far away and then travel to the end slot, while the rest of the slots simply snap into their new position, without transitioning.

Note, that the Icons and Empty slots are not parented to one another, they are seperate objects, and a script is being used to make one travel towards the other.

#

Does anyone have any clue why my Insert slot function might be behaving wrong?

#

It's correctly setting the icon to the intended target, but visually, it's snapping in ways I'm uncertain of.

wicked stratus
#
        photographedGridTiles = AssetDatabase.LoadAllAssetRepresentationsAtPath("Assets/art/Grids/PhotoGrid.png");

is it possible to turn these objects into sprites? it's loading in the correct objects and the correct amount of objects but I'm not sure how to get those objects (individual sprites) into objects

wicked stratus
#

how can I do that

rich adder
#

loop then do as Sprite

wicked stratus
#

well i know to loop but how would it go for the object to sprite? i.e. photographedGridTiles[i].turnintosprite

wintry quarry
#

Unless these things are ALREADY sprites

#

In which case you don't need to turn them into one

rich adder
#

its a spritesheet i think

wicked stratus
#

they are already sprites.

wintry quarry
#

Then there's nothing to turn into anything

wicked stratus
#

let me describe my problem i suppose

wintry quarry
#

Use the generic forms of the functions from AssetDatabase

wicked stratus
#

I have a spritesheet sliced into 300 sprites and want to load these in programmatically.

#

the Resources.LoadAll is giving me issues

wintry quarry
#

Use this

rich adder
#

do Object[] data = AssetDatabase.LoadAllAssetsAtPath

wintry quarry
#

The generic form if it exists

#

Otherwise just cast them after

wicked stratus
#

typecast like this?
(Sprite)photographedGridTiles[i];

wintry quarry
#

Yes

#

Or using if (theThing is Sprite s) s.whatever();

#

That's a bit safer

wicked stratus
#

it did the same thing (I believe made them objects rather than sprites, but also imported the image itself and put 7 there for some reason

wintry quarry
#

Wdym "it did"? Show your code

#

Loop through and only take the Sprites

#

The asset file is going to contain the texture as well as the Sprites

covert sinew
rich adder
#
if(data[i] is  Sprite sprite)
{
    SpriteList.Add(sprite);
}```
covert sinew
#

And I'm not sure how to force them to obey the hierarchy.

wicked stratus
# wintry quarry Wdym "it did"? Show your code
photographedGridTiles = AssetDatabase.LoadAllAssetsAtPath("Assets/art/Grids/PhotoGrid.png");
radargridTiles = AssetDatabase.LoadAllAssetsAtPath("Assets/art/Grids/PhotoGridRadar.png");
  for (int photoIndex = 0;  photoIndex < 300; photoIndex++)
        {   tempGridObjectClass[photoIndex].radarPicture = (Sprite)radargridTiles[photoIndex];
            tempGridObjectClass[photoIndex].picturedPicture = (Sprite)photographedGridTiles[photoIndex];
        }

I set the sprite image programmatically later.

#

oh- hold on

#

ok it works now

#

thank you both

covert sinew
#

Yeah, I've done some testing, and when I instantiate an object, setting its child index in the same function does not work, the new object will still appear at the end of the hierarchy.

#

I'm not sure what's going wrong.

rich adder
covert sinew
#

Removing Items and Adding Items to the end of a list work correctly, but when I add an item to the middle of the list, it does not set the new icon's sibling index to match that of the index provided in the function.

#

Instead, the new instantiated icon is ALWAYS at the end of the hierarchy, even after using SetSiblingIndex on it.

#

even in the editor menu, I can see the new icons are being added to the end of the hierarchy, no matter what.

rich adder
#

your inventory display could probably simpler than this

covert sinew
#

I don't know how, and that isn't exactly useful to solving this problem. I just want to spawn an object, then set its place in the hierarchy in the same function.

#

The inventory is working just fine, it's just that it's not correctly adding icons to the middle of the hierarchy, but instead exclusively adds them to the end.

last basin
#

hi guys, can we detect the collision of a child object ?
My cone is a child of the ghost, i want to detect collision of both with the player and do two different action.
The script for the ghost is in the ghost.

teal viper
last basin
#

Okay ty, my ghost doesn't have a rg, my player has one

wintry quarry
last basin
#

Oh ok i've had a rb, ty

    void OnTriggerEnter(Collider other)
    {
        Debug.Log(other.transform.IsChildOf(transform));
        if (other.transform.IsChildOf(transform) && other.CompareTag("Player")) {
            Debug.Log("ON GHOST");
            followingPlayer = true;
            playerTransform = other.transform;
            followTimer = 0f;
        }
        // else if (other.CompareTag("Player"))
        //     SceneManager.LoadScene(0);
    }``` I try that but my debug.log never return true  🤔
wintry quarry
visual hedge
#

hello there

    private void Start()
    {
        curLvl = UnitLevel.level.currentlevel;
        UnitLevel.level = new Level(curLvl, OnLevelUp);
    }

and

    public Level(int level, Action OnLevUp)
    {
        MAX_EXP = GetXPForLevel(MAX_LEVEL);
        currentlevel = level;
        experience = GetXPForLevel(level);
        OnLevelUp = OnLevUp;
        requiredExp = CalculateRequiredExp(level);
    }

and

    public bool AddExp(int amount)
    {
        if (amount + experience < 0 || experience > MAX_EXP)
        {
            if (experience > MAX_EXP)
                experience = MAX_EXP;
            return false;
        }
        int oldLevel = GetLevelForXP(experience);
        int nextLevel = oldLevel + 1;
        experience += amount;
        if(oldLevel < GetLevelForXP(experience))
        {
            if(currentlevel < GetLevelForXP(experience))
            {
                currentlevel = GetLevelForXP(experience);
                if (OnLevelUp != null)
                    OnLevelUp.Invoke();
                    requiredExp = CalculateRequiredExp(currentlevel+1);
                return true;
            }
        }
        return false;
    }

Problem: while there's only one hero subscribed to this, it's all okay.
As soon as 2 are subscribing = disaster.
What can I do to make this system work for many?

wintry quarry
#

And what do you mean by subscribed? I'm not seeing any events

last basin
wintry quarry
#

Because that's what that code checks

last basin
#

Oh

visual hedge
# wintry quarry What does "disaster" mean?

basically as only 1 character is "online" and using it, it gains exp properly.
As soon as I use this code here:

    private void Start()
    {
        curLvl = UnitLevel.level.currentlevel;
        UnitLevel.level = new Level(curLvl, OnLevelUp);
    }
``` on another, and 2 are in the game at the same time, both are getting exp, but it starts with previous value always. With the one character were loaded into the game. 
LEt's say character loaded with 1300 exp and got 120 exp for the battle.
At the start of next battle exp is 1420, seems fine, till it gets exp again. Let's say he gets 50. Now after leving the battle hero will have 1350.
last basin
#

but why C# transform.IsChildOf(transform) return true on all collision ?

wintry quarry
visual hedge
#

I simply can't debug the problem. Just saw that while only 1 unit is using the thing, it's totally fine. As second one were enabled = it's all nuts.

wintry quarry
#

True by technicality if you look at the docs for IsChildOf

visual hedge
wintry quarry
#

If the problem is that you're gaining too much experience or too little experience, I would start by checking when and where the code that gains experience is running and on which objects

visual hedge
wintry quarry
#

but sounds like probably you are storing the same value in multiple places and losing track of what the "true" value is

wintry quarry
visual hedge
wintry quarry
#

and where do these variables even get declared

visual hedge
wintry quarry
#

So you don't understand the code at all, it's natural you're having trouble debugging it

last basin
wintry quarry
#

anyway this is going to raise my blood pressure right now and I should be asleep

#

so I shall go to sleep

visual hedge
silent vault
#

Hello everybody, newbie question: Is it ok for one gameobject to have several trigger colliders of various sizes with one rigidbody. The idea is to check different things, like if gameobject is inside a zone, colliding with specific objects which have different trigger distance.

#

Or should I create 1 child gameobject with collider + kinematic rigidbody instead ?

teal viper
#

If you need to differentiate between the colliding colliders, it's better to have them on separate objects with their own rbs.

silent vault
#

what is rbs ?

last basin
silent vault
#

Why is it better for them to have their own rigidbody if all those child rigidbody will have the same parameters ?

teal viper
#

Don't you want to know which one collided?

#

Did I misunderstand the question?

#

If you have several colliders bound to one rb, they're considered a compound collider and it becomes difficult to know which of the colliders was responsible for a collision.

silent vault
#

In this case, I don't need to add so many child rigidbodies, right?

#

I'm asking because I'd like to create a kind of moba game where soldiers need to capture points. so I'd need a collider to check waypoints, check if they are inside capture zone and a shooting collider too of course.

teal viper
silent vault
#

But since I'll have many soliders, I'm worried having so many child rigidbodies might put an unecessary strain on the game

silent vault
teal viper
silent vault
teal viper
#

Best to go with the simple solution first and test and profile as you go

silent vault
#

But having specific layers collisions should reduce collider calculation too, right?

#

Hm, true.

teal viper
silent vault
#

I'm just worried after the code becomes more complex, it'll be hassle to change

silent vault
teal viper
#

If the code is designed in a good way, refactoring one part shouldn't be a problem

silent vault
#

True, Unity is quite nice to work with on this aspect.

#

Ok, I'll got with children then, it'll be clearer indeed. Thanks for the help.

potent nymph
#

in hlsl, how do I check if a variable is unassigned/undefined? Null doesn't work either
if (waterPointsLength != null) {

teal viper
native seal
#

-1 is typically used for types like int to show null

#

if that fits ur case

potent nymph
#

okay, thanks for clarifying

native seal
#

you could use that

potent nymph
#

I just used 0 for null

#

-1 could work

native seal
#

length can never be negative so it makes sense

#

it could be 0

radiant frigate
native seal
#

use a coroutine i think

radiant frigate
#

its a coroutine

native seal
#

oh then lerp the value

teal viper
#

It executes completely immediately

radiant frigate
#

i have tried with a for but it also makes it immediately

teal viper
#

You need to yield inside the loop if you want it to execute over time

radiant frigate
#

true

native seal
#

wouldnt it just be better to lerp?

#

or am i mistaking how that works

radiant frigate
#

what is lerp?

native seal
#

interpolates between two values

teal viper
native seal
#

ah okay

#

you could use DOTween

#

its on github

radiant frigate
#

nah im going to stick with the yield i think

#

but i will check it out for sure

native seal
#

dotween lets you make a curve as well

#

so if you want it to start slow then speed up or visa versa its cool

radiant frigate
#

i want it to be linear but i could use that for other things

#

omg it looks so cool now

teal viper
#

You can have linear interpolation with dotween as well. Probably(havn't used it).

#

But it would be weird if they didn't have that option

radiant frigate
teal viper
#

It could help you get rid of a lot of boilerplate code. I don't think that analogy is correct in this case. DOTween is specifically for interpolating values over time.

radiant frigate
#

i havent used it nor seen it so i may be just talking shit but for what it sounds like it seems usefull for things that are a bit more complex, i just want to augment something overtime by the same value

native seal
#

dotween is super simple

#

it makes a whole couroutine function that is inefficient into one line

radiant frigate
#

then i should learn it

native seal
#

takes like 2 minutes

radiant frigate
#

imma write a reminder on that

#

yeah but i want to finish this since i gotta leave in a while

native seal
#

👍

teal viper
native seal
#

yea for sure, just super helpful

#

no real reason to try to reinvent the wheel i guess

misty coral
#

im coding a script for enemies that when the raycast from a gun object its the enemy object 10 times it disapears

#

but with multiple enemies

#

no matter which one i am at

#

shooting at one takes the health bar down of a certain one

native seal
#

i have the same thing in my game ``` private void Pierce(IDamagable damagable)
{
if (numberOfHits <= pierce)
{
if (damagable != null)
{
damagable.TakeDamage(damage);
numberOfHits++;

            if (numberOfHits > pierce)
            {
                Destroy(gameObject);
            }
        }
    }
}```
#

if you want to reference it

misty coral
#

is there something i need to do to make unity tell the difference between the enemy objects?

#

since it only works with one

native seal
#

the logic should be on the projectile

#

this function is called when it hits a collider

misty coral
#

this is what i am handling in my gun object code

native seal
#

oh with raycasts its a bit different

wintry quarry
native seal
#

you need to only apply the changeHP to the first 10 enemies

misty coral
native seal
#

it has an out

wintry quarry
native seal
#

which contains all the colliders

wintry quarry
#

It tells you details about what you hit

lilac olive
#

Hey, is it possible to "Capture" a Full screen
EG like Discords ScreenShare in Unity

I'm trying to make a Virtual Workspace App for VR but need to mirror the Users Screen to the Game Monitor
is this possible or do i need a different approach than Unity

misty coral
#

@misty coral I will look back here later

wintry quarry
#

Instead you're reducing hitpoints on some random other reference you have from elsewhere in the script

#

Think about it

native seal
#

maybe consider using RaycastAll

wintry quarry
#

Why would they do that and how would it simplify things?

native seal
#

loop through the first 10 enemies returned

wintry quarry
#

They're saying the enemies have 10 hitpoints

native seal
#

oh

#

i misunderstood it

radiant frigate
queen adder
#

I hope we can make Resources.Load target other folders as well

#

Resources is waaaaaaaaaaaaaaaaay too far in the alphabet

teal viper
queen adder
#

yea so i either go with one of these

#

either toooo far, or ugly folder chain 🥹

#

im kinda getting bothered by clicking 2 folders just to work on somewhere 👉 👈

teal viper
#

It's not even recommended anymore

pallid sand
#

I am using Unity Editor 2023.2.3f1 and any changes in Animator during runtime will break animation

silent vault
#

How should I handle a capture zone if the player can die on the zone but still be revive? I attached a collider on the player and one on the zone so a simple collisionenter will trigger the capture but how do I check for a stop capture easily? The player can be shot down but his collider would still be in the zone so it won't trigger the collisionexit. Would disabling the collider while dead trigger the collisionexit?

wintry quarry
silent vault
silent vault
# wintry quarry Stop capturing when the player dies, that's all

I'm still hesitating to use this solution in the end because there might be other ways for capture to be stopped and it might be hard to track everything, plus the fact that zone capture code would be split in other scripts. I'm looking at OnTriggerStay now and I'm wondering if it would be a heavy operation to add there directly ?

#

I guess I'll go with triggerstay first since it seems safer to use though less performant. I'll look into it further if I get performance issue in the future.

wintry quarry
olive lintel
#

https://hastebin.com/share/acuritiwev.csharp
Hey guys, would anyone be able to tell me why the localRotation of my hands doesnt seem to be lerping correctly? I think the issue lies in how I'm using Quaternion.Lerp, as I am able to assign the localRotation correctly at the end of the "animation"

wintry quarry
#

The capture code should be pulled out of physics callbacks entirely and managed centrally from the zone.

olive lintel
wintry quarry
olive lintel
#

rot lerp is returning values between 0 and 1

#

so thats not the issue

#

only thing I could find to be the issue is quaternion.lerp returning bogus values for some reason

#

idk why

wintry quarry
#

Slerp is correct for rotation. Lerp is for linear motion.

#

I suggest adding logs to both of these functions

#

Make sure the binding one isn't running multiple times for example

olive lintel
#

the targrot in the scriptable object was quaternion.identity

#

or atleast it was exposed as (0, 0, 0) in the inspector

#

setting it to (1,1,1) for each of them fixed it

#

kinda weird but hey its fixed I cant complain lol

#

thank you for your time

wintry quarry
#

That doesn't sound right... Something is definitely off.

olive lintel
#

I've no idea why but when I was making a script for hand bobbing

#

it would sometimes crash when trying to lerp between quaternion.identity and another quaternion

#

really weird but I just added a check to make sure it isn't quaternion.identity and if so change the starting/ending rotation to quaternion.euler(1,1,1)

#

really weird but my unity version seems to hate quaternions I have inspector issues too

silent vault
#

But trying to implement it, you're right, my idea is wrong, that's not how triggerstay work. I was thinking it would give me all the colliders in the zone at once but it only work one by one. There would be a physics.overlap solution but that would also seem backward. I'll stick with the original die modification idea then and simply add a list of units in the zone with triggerenter and triggerexit myself rather than trying to calculate it at once.

eternal needle
olive lintel
ivory bobcat
eternal needle
eternal needle
olive lintel
#

I'm on 2021.3.1f1

olive lintel
languid spire
olive lintel
languid spire
#

the early versions of ALL LTS's are very buggy and should be avoided

hidden sun
#

hi, any idea how to make methods for these anonymous functions?

#

i dont know what to do with @event

olive lintel
#

and updates for it would automatically install

languid spire
#

Also I don't think Quaternion is your problem
this code

        Quaternion q = new Quaternion(0, 0, 0, 0);
        Debug.Log(q);
        transform.rotation = q;
        Debug.Log(transform.rotation);

produces this output

olive lintel
#

but during quaternion.lerp it just returns bogus values

#

it was changing that targRot value to (1, 1, 1) in the inspector that fixed it but eh idk

olive lintel
magic pagoda
#

heyy can someone explain this bug to me real quick please?

I tried looking it up but... to no avail -.-"

ivory bobcat
#

What bug?

languid spire
magic pagoda
magic pagoda
languid spire
#

do you know what a meta file is?

magic pagoda
#

no, sorry ^^;

languid spire
#

never mind. Close your project. Delete the Library and Temp folders in your project. Open your project. It should clear the error but may take a while

magic pagoda
#

is that really the only solution??

languid spire
#

no, but there is no way I'm going to explain the details of how Unity works in 3 sentences

magic pagoda
#

Im.. gonna look it up some more

wary dagger
queen adder
#

how to avoid those weird unity messages? they are just being spammed

#
if (value > 0)
{
    GetComponent<Text>().color = Color.green;
    GetComponent<Text>().text = "$" + value.ToString();

} else
{
    int fixedVal = Mathf.Abs(value);
    Debug.Log(fixedVal);
    GetComponent<Text>().color = Color.red;
    GetComponent<Text>().text = "-$" + fixedVal.ToString();
}

Why the text changes to "-$" instead of "-$5"?
The debug.log says 5 as it should be

#

oh wait the text changes correctly but it seems like it cannot fit

magic pagoda
languid spire
young ember
#

I want to make a human model(That i downloaded from random site) Move Is there way to make it possible(With walking Animation)?
If i made it my self do i need To make Animation for it or i can just add velocity to diffrent parts of the body?

keen dew
#

If you want it to look even remotely realistic, you'll have to make an animation. Adding velocity would at best make it look something like this

winged granite
#

I made a pixelated retro effect on my game with the Render Texture Technique
the thing is, when I drag n drop my texture in PlayerCamera>TargetTexture, it shows the effet but not the UI anymore (like the crosshair, stamina...) and shows this:

#

how can i fix that??

#

(ping me if u have an answer pls)

bright zodiac
smoky mauve
#

why isnt the class carrera apearing in the inspector?

spiral narwhal
#
        controls.Player.Move.performed += ctx => _moveInput = ctx.ReadValue<Vector2>();
        controls.Player.Move.canceled += ctx => _moveInput = Vector2.zero;

If I press A and D at the same, why is _moveInput.x equal to 0? There is no other code involved that changes the variable

keen dew
smoky mauve
spiral narwhal
#

The value of the last pressed key, at least that was what I expected it to be

#

So if A is pressed, the value is -1, if then also D is pressed I expected it to be 1, instead of 0

keen dew
#

The input system assumes that trying to move left and right simultaneously cancels each other out

spiral narwhal
#

Haha ok then

#

Thanks

bright zodiac
#

on hardware level the terms used is SOCD cleaning

spiral narwhal
#

Interesting, I'll read up on it, thanks

wary dagger
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ShootingSystem : MonoBehaviour
{
    [SerializeField] private Transform StartPosition;
    [SerializeField] private GameObject AOE;
    [SerializeField] private PlaneCreator Ground;
    [SerializeField] private bool isShooting;
    private GameObject highlight;

    private void Update()
    {
        if (Input.GetButton("Fire1"))
        {
            if (Input.GetButtonDown("Fire1"))
            {
                highlight = Instantiate(AOE, StartPosition.position,Quaternion.identity);
            }

            if (highlight != null)
            {
                Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

                if (Ground.Plane.Raycast(ray, out float enter))
                {
                    Vector3 hitPoint = ray.GetPoint(enter);
                    hitPoint.y = StartPosition.position.y;

                    Vector3 direction = (hitPoint - StartPosition.position).normalized;

                    Quaternion rotation = Quaternion.LookRotation(direction);

                    highlight.transform.rotation = rotation;
                    highlight.transform.position = StartPosition.position;
                }
            }
        }
    }
}

why is the object rotating only if the cursor is far away enough from the player?

ionic zephyr
#

how can i add momentum to movement?

timber tide
#

you put your left foot in, you put your right foot out

ionic zephyr
#

inertia

buoyant knot
#

ie velocity needs to change proportional to deltaTime

ionic zephyr
#

okay, thanks a lot, let me try

timber tide
ionic zephyr
tall delta
limpid wren
#

I'm making a system where some UI elements are alternating between being activated and deactivated repeatedly (think a blinking "warning" sign).

Obviously there are a lot of ways to repeat the same action over and over, Coroutines, using a timer, etc. But those solutions all feel somewhat dirty to me. Is there a pattern for this I'm not aware of?

timber tide
#

coroutines are fine

limpid wren
#

Even if I just want it running forever?

timber tide
#

yeah, that or using tasks

tall delta
queen adder
limpid wren
#

Just seems like a lot of code to do essentially

timeUntilNextBlink -= Time.deltaTime;
if(timeUntilNextBlink < 0)
//dostuff

In update

timber tide
#

honestly I'd just yield wait

#

sleeping coroutines better than having to check

limpid wren
#

The warning siren isn't constantly on

tall delta
#

something like this, curtesy of gpt

public class BlinkBehavior : MonoBehaviour {
    public float blinkInterval = 1.0f; // Time between blinks
    public bool enableBlink = true; // Toggle the blink behavior on or off
    public float timeToLive = -1.0f; // Time to live in seconds, negative for infinite

    private float timeSinceLastBlink = 0.0f;
    private float lifeTimer = 0.0f;
    private bool isInitialized = false;

    void OnEnable() {
        if (!isInitialized) return;
        timeSinceLastBlink = 0.0f;
        lifeTimer = 0.0f;
    }

    void Start() {
        isInitialized = true;
    }

    void Update() {
        if (!enableBlink) return;
        if (timeToLive >= 0) {
            lifeTimer += Time.deltaTime;
            if (lifeTimer >= timeToLive) {
                gameObject.SetActive(false);
                timeSinceLastBlink = 0.0f;
                lifeTimer = 0.0f;
                return;
            }
        }
        timeSinceLastBlink += Time.deltaTime;
        if (timeSinceLastBlink >= blinkInterval) {
            gameObject.SetActive(!gameObject.activeSelf);
            timeSinceLastBlink = 0.0f;
        }
    }

    public void SetBlinkEnabled(bool enabled) {
        enableBlink = enabled;
        if (enabled) {
            timeSinceLastBlink = 0.0f;
            lifeTimer = 0.0f;
        }
    }
}

not to say, using a coroutine or an async method are also totally valid

limpid wren
#

Ah cool

#

If I may ask, what's the "if (!isInitialized) return;" pattern for

#

I've seen it before but it's not entirely clear to me why people use it

buoyant knot
#

and I mean just in general, deltaVel should be proportional to the time step

tall delta
wary dagger
buoyant knot
#

OnEnable gets called immediately, right after awake, and that might be your chance to get shit going.

limpid wren
#

I see, but wouldn't I use "Awake" to initialize most things

buoyant knot
#

Yes, but sometimes you need shit ready before a given event

#

like let’s say that I instantiate something in a trigger callback

#

Start will not get called until next frame

#

now collision callbacks happen, and I find that script, and need to do something on it

#

problem: it hasn’t had its Start() called yet!

tall delta
limpid wren
#

Right

buoyant knot
limpid wren
#

But if I make a new object, Awake is called immediately, right?

buoyant knot
#

And in the aforementioned scenario, Start has not been called yet when you need it

limpid wren
#

Like if I instantiate a new object

limpid wren
#

So as long as whatever setup the object needs to run is dealt with in "Awake" it's safe to immediately use that object afterwards

#

and in "Start" I should only put less time-sensitive things like accessing or connecting to other objects

buoyant knot
#
Instantiate(blah);
Debug.Log(“after”);```
If each script on blah has Debug.Log(, then you would see in debug log:
-before
-A Awake
-A OnEnable
-B Awake
-B OnEnable
-“after”
timber tide
#

Awake for all that is non-dependent, Start for all that is dependent

buoyant knot
#

the way to think about it is:
-Start has one time in the frame where it gets called
-Start also gets called if you are about to call (or try to call, even if not defined) Update, FixedUpdate, or LateUpdate, if it has not been called yet

#

that is how I think it works but unity docs aren’t super clear

#

what you need to know is that you can only depend on Awake and OnEnable to go off on the frame that you come into existence

#

Start is a kind of shitty initialization method imo. Convenient, but not totally reliable on timing

timber tide
#

the secret is to just not use these methods and use assignment methods which then enable update

buoyant knot
#

yeah. I use those when timing matters

#

I don’t have a general interface for this, because I usually need to call Initialize( as a function with actual arguments

swift crag
#

yeah, I have a few places where I explicitly "init" my objects

#

I don't use Awake or Start for any of my UI components, save for the roots. They get set up by a parent object.

buoyant knot
#

I use Awake a lot

#

Awake is totally reliable

#

i usually grab my singletons in awake

#

or any GetComponent calls

#

or initialize any arrays etc

tall delta
#

OnEnable/Disable are also invaluable when dealing with event registration imo

swift crag
#

I'm avoiding Awake in that case because I need to have some data set by whoever instantiates the component

#

a SettingList needs to be told what setting category it's going to be displaying

buoyant knot
#

yeah, don’t set data in Awake. that will fuck you up

#

but awake should include any initialization activities that are independent of the contents of any other objects

#

After Awake, you should be able to call shit without getting NREs and constantly checking for null

#

also, I wish NRE would tell you which variable was null

ionic zephyr
#

I still dont know how to add inertia

#

I tried addforce

#

but still doesnt work

buoyant knot
#

any system where velocity changes proportional to your time step will have inertia

#

example:
velocity += acceleration * deltaTime;

ionic zephyr
#

and what about if I am using fixedUpdate

buoyant knot
#

example:
targetVel = controlStickVector * maxSpeed;
velocity = Vector2.MoveTowards(currentVel, targetVel, acceleration * deltaTime);

buoyant knot
#

also i’m talking about your time step, dude. not the specific variable

#

rb.AddForce(force. ForceMode.Force)
effectively does:
velocity += deltaTime * force / mass;

#

it calculates the acceleration, using Newton’s second law

ionic zephyr
#

Okay, let me try, thanks!

buoyant knot
#

btw
rb.AddForce(force, ForceMode.Impulse);
does:
velocity += force/mass;
which is not proportional to timestep

#

and just saying:
velocity = maxSpeed * controlStickVector;
is also not proportional to time step

ionic zephyr
#

Okay, got it

#

And what about if I wanted to make that force a problem for the player?

#

How could I make it so that it is difficult to controll?

buoyant knot
#

the lower the acceleration rate or force, the less responsive it will feel

buoyant knot
ionic zephyr
#

so if I write rb.AddForce(little force, ForceMode.Force) is less responsive?

buoyant knot
#

the change in vel will be less

swift crag
#

A small force will make you more sluggish, yes

#

Your acceleration will be lower, so it will take longer to change your velocity.

ionic zephyr
#

Okay, thanks a lot guys

lost anvil
#

im having a problem where; once the AI exits the chase state and into the patrol and back into chase, he remains the same 1.5f patrol speed, which is also the same speed as the ai slows down to 8 seconds into chase. i think the problem is to do with the DOTween near the bottom? im not sure tho

code - https://gdl.space/ehewifesik.cs

buoyant knot
#

also make sure your units are right

buoyant knot
ionic zephyr
#

is this correct?

buoyant knot
#

deltaTime has units of time.
position has units of meters
velocity in m/s
mass in kg
force in kg m / s^2…

#

you cannot add inertia

#

inertia is a thing you have

#

and inertia is also not a vector

#

it is a concept

#

inertia is tied to mass

#

acceleration = force / mass
deltaVel = acceleration * time
Bigger mass makes your change in velocity less

swift crag
#

a higher "inertia" value would make you accelerate faster here, so that's definitely not right.

buoyant knot
#

do not add a vector to compensate. Just calculate what the movement is supposed to be, and apply

sonic kestrel
#

Do you know a video about how can I control my 2D character? I tried 2 hours and I can't manage to moving my character.

rare basin
#

just use tool called "google"

buoyant knot
ionic zephyr
buoyant knot
#

you keep jumping into your code without a plan, then waste time because the math was wrong

rare basin
swift crag
#

instead of having a variable for "sluggishness", i would suggest having a variable for force

#

a sluggish character has a low force

#

or has a high mass

#

If everyone has the same force, then heavy characters will feel sluggish and light characters will feel quick

#

If everyone has the same mass, then high-force characters will feel quick and low-force characters will feel sluggish

#

Different masses will mean that heavy characters are hard to push around with light characters.

near yarrow
#

Is it possible to convert PPtr<MonoScript> to fileId and guid from m_Script?

sonic kestrel
#

Finally I solved

north kiln
near yarrow
#

yea I missed the channels sorry

north kiln
near yarrow
rich bluff
#

i think you just never kill the coroutines

#

so SlowDownChump() keeps running after state change

buoyant knot
#

I have a level editor with hotkeys, and I’m contemplating using a command pattern so there is a unique command each frame.

vagrant lynx
#

Guys, how to get good at coding movement scripts ??

buoyant knot
#

Any recommendation on how to implement?

rare basin
#

and google

rich bluff
glass cairn
#

I have this line of code but I want to switch the mouse press with a key press of E, what would I write?

vagrant lynx
rare basin
#

how to detect button press in unity

glass cairn
#

i keep getting results for some enhanced input system

rare basin
#

google isnt hard to use

buoyant knot
# vagrant lynx Guys, how to get good at coding movement scripts ??
  1. Separate contact/grounding/specific surface detection into a different class
  2. Use timestamps to log inputs and when you touch ground. Do not store bools for inputs.
  3. Use an enum to represent the current state of your player
  4. Animation and life/death logic needs to go into a different class from movement
buoyant knot
glass cairn
#

I rlly just needed to change my wording for google damn

rare basin
#

google is a skill you need to learn

buoyant knot
quartz mural
#

anyone know how to fix an out of bouds error