#💻┃code-beginner

1 messages · Page 41 of 1

inner marsh
#

right

wintry quarry
#

Prove that the function exists

rich adder
#

Inventory is not an easy thing to dive into in the beginning 🙂 they vary in complexities but tomorrow Im at my main pc, I can show you a few examples I have from old tut

inner marsh
#

RemoveItem and AddItem are from the equipmentpanel script, which i reference, which in turn means it should work

acoustic arch
wintry quarry
#

Read the error

inner marsh
#

in the inventory script

#

yes it does

wintry quarry
#

Prove it

inner marsh
#
    {
        return items.Count >= itemSlots.Length;
    }```
wintry quarry
#

Show the full script

#

Without context who knows where that is

inner marsh
#
using System.Collections.Generic;
using UnityEngine;
using System;

public class Inventory : MonoBehaviour
{
    [SerializeField] List<Item> items;
    [SerializeField] Transform itemsParent;
    [SerializeField] ItemSlot[] itemSlots;
    public event Action<Item> OnItemRightClickedEvent;

    private void Awake()
    {
        for (int i = 0; i < itemSlots.Length; i++)
        {
            itemSlots[i].OnRightClickEvent += OnItemRightClickedEvent;
        }
    }
    private void OnValidate()
    {
        if (itemsParent != null)
            itemSlots = itemsParent.GetComponentsInChildren<ItemSlot>();

        RefreshUI();
    }
    private void RefreshUI()
    {
        int i = 0;
        for (; i < items.Count && i < itemSlots.Length; i++)
        {
            itemSlots[i].Item = items[i];
        }
        for (; i < itemSlots.Length; i++)
        {
            itemSlots[i].Item = null;
        }
    }
    public bool AddItem(Item item)
    {
        if (IsFull())
            return false;

        items.Add(item);
        RefreshUI();
        return true;
    }
    public bool RemoveItem(Item item)
    {
        if (items.Remove(item))
        {
            RefreshUI();
            return true;
        }
        return false;
    }
    public bool IsFull()
    {
        return items.Count >= itemSlots.Length;
    }
}```
wintry quarry
#

It could be a local function for all I know

rich adder
inner marsh
#

jesus christ

wintry quarry
inner marsh
#

yes

#

and i reference the inventory script

#

holy fuck

wintry quarry
#

That makes no sense

#

Slow down

#

Don't get upset

inner marsh
#

mbmb

wintry quarry
#

I'm explaining your problem

#

You are calling the function on the wrong object

#

Show where you call the function

inner marsh
#
    {
        if (Inventory.RemoveItem(item))
        {
            EquippableItem previousItem;
            if (EquipmentPanel.AddItem(item, out previousItem))
            {
                if (previousItem != null)
                {
                    Inventory.AddItem(previousItem);
                }
            }
            else
            {
                Inventory.AddItem(item);
            }
        }
    }

    public void Unequip(EquippableItem item)
    {
        if (!Inventory.IsFull() && EquipmentPanel.RemoveItem(item))
        {
            Inventory.AddItem(item);
        }
    }``` in the inventory manager script
wintry quarry
#

Show that variable definition

inner marsh
wintry quarry
#

Make sure you saved all of your scripts

#

Because the error is clearly saying you tried to call it on an InventoryManager

#

What is the filename and line number of the error

inner marsh
#

fixed that and now its js saying this Inventory.OnItemRightClickedEvent += Equip;

inner marsh
#

mb for ts im tired asffff

rich adder
#

your method has the wrong type

wintry quarry
#

Your delegate expects Item but your function has EquippableItem

inner marsh
#

okay, what would you reccomend to fix that?

ashen ferry
#

doesnt ide autofill that for u after the +=

wintry quarry
#

Make another function that takes Item as the param and tries to cast it to EquippableItem and if so calls that function

rich adder
ashen ferry
inner marsh
#

pisses me off

ashen ferry
#

bro this configuration thing is biggest meme for me personally cause I legit never configured it myself only set default editor in settings thing

rich adder
#

configuring wont work while you have compiler error

ashen ferry
#

it just comes configured what yall do

inner marsh
ashen ferry
#

aa idk abt vs code

rich adder
ashen ferry
#

giga stupid question but if ive got Color32 property and now I want to check if its set to anything at all what do I do? check if its not 0,0,0,0 ? why != default doesnt work

wintry quarry
rich adder
#

unless they have some override for == that wont work cause of floats

wintry quarry
#

It has to be set to something

I think the default might be white though

#

Not clear

ashen ferry
#

I have class with Color32 property and constructor with optional param to set Color32 to something so if I dont use that param to set the color

#

what is it its not null

rich adder
#

its a struct

wintry quarry
#

It's a struct they can't be null

rich adder
#

cant be null

ashen ferry
#

yea thats the problem

wintry quarry
#

If you want it nullable use a nullable type

ashen ferry
#

so how do I check if it has been set to smthn

#

aa right

#

forgor

wintry quarry
#

Use a separate bool

#

Or nullable type

ashen ferry
wintry quarry
#

E.g. Color32?

robust stirrup
#

Sorry, busy day. I will look into this one!

#

This is the error I get with this script I made now

[UdonSharp] Source C# script on TextureSwapper (UdonSharp.UdonSharpProgramAsset) is null
UnityEngine.Debug:LogError (object,UnityEngine.Object)
UdonSharp.UdonSharpUtils:LogError (object,UnityEngine.Object) (at Packages/com.vrchat.worlds/Integrations/UdonSharp/Editor/UdonSharpUtils.cs:329)
UdonSharp.Compiler.UdonSharpCompilerV1:Compile (UdonSharp.Compiler.UdonSharpCompileOptions) (at Packages/com.vrchat.worlds/Integrations/UdonSharp/Editor/Compiler/UdonSharpCompilerV1.cs:285)
UdonSharp.UdonSharpProgramAsset:CompileAllCsPrograms (bool,bool) (at Packages/com.vrchat.worlds/Integrations/UdonSharp/Editor/UdonSharpProgramAsset.cs:295)
UdonSharpEditor.UdonSharpGUI:DrawUtilities (UdonSharp.UdonSharpProgramAsset) (at Packages/com.vrchat.worlds/Integrations/UdonSharp/Editor/Editors/UdonSharpGUI.cs:393)
UdonSharp.UdonSharpProgramAsset:DrawProgramSourceGUI (VRC.Udon.UdonBehaviour,bool&) (at Packages/com.vrchat.worlds/Integrations/UdonSharp/Editor/UdonSharpProgramAsset.cs:204)
UdonSharp.UdonSharpProgramAssetEditor:OnInspectorGUI () (at Packages/com.vrchat.worlds/Integrations/UdonSharp/Editor/UdonSharpProgramAsset.cs:601)
UnityEngine.GUIUtility:ProcessEvent (int,intptr)

sturdy lintel
#

At first when the initial line is dragged, the travelling balls, move perfectly even after changing the endPoints of the line. Now when another line is created, the balls move perfectly as I want. The issue arises when I try to move the first line after the 2nd line is created. Then as shown in video, the balls don't move along the 2lines.

I have 2 scripts as follows:

#

Can someone tell me what the issue is?

rich adder
#

I never used Udon sharp

robust stirrup
#

Yeah, i made a copy of it to see if it was just a import error

eternal falconBOT
queen adder
#

how to reload a scene without using loadscene twice?

sturdy lintel
robust stirrup
# rich adder I never used Udon sharp

It was an import error, but now its telling me Assets/UdonSharp/UtilityScripts/TextureSwapper1.cs(31,5): Nested type declarations are not currently supported by U#

Is there something I did wrong in the code?

queen adder
sturdy lintel
#

Alright wait, thanks

wintry quarry
queen adder
#

it is inconvenient for people to help with discord turning your codes into file

queen adder
wintry quarry
wintry quarry
#

Unless you're using additive loading

queen adder
#

ah yea me is using that

wintry quarry
#

Why

#

If you want to unload why use additive

queen adder
#

loading bar blushie

wintry quarry
#

That's async

#

Not additive

queen adder
#

oh

wintry quarry
#

Anyway that'd involve a second scene (loading scene)

robust stirrup
queen adder
#

i can just reload the same scene and nothing bad will hapen?

queen adder
#

havent tried it before, lemesi

robust stirrup
wintry quarry
#

99% chance you don't need to edit the framework to fix your issue

robust stirrup
#

public enum Texture_OR_Material

#

thats line 31

rich adder
#

but why

robust stirrup
#

its telling me 31,5 is not supported, I had it as
public enum Texture OR Material
not
public enum Texture_OR_Material

rich adder
#

yeah u cant have spaces in the variable name

robust stirrup
#

but it still says not supported

wintry quarry
#

The first one is nonsense

wintry quarry
#

Delete it and reinstall from the source and make sure you follow their instructions on unity version etc

wintry quarry
#

This kind of GameObject name shenanigans are a bad idea

#

And GameObject.Find is a bad idea

rich adder
#

that looks unholy af

wintry quarry
#

Use real object references

sturdy lintel
wintry quarry
#

What you're doing is causing your problems

#

It's not about optimisation

#

This isn't a way to do things

sturdy lintel
#

what do I do exactly?

gaunt ice
#

use script to differentiate it and store data

sturdy lintel
north kiln
#

It isn't that straight forward, but you should try to encapsulate your logic better

#

one of the code smells I see is having class-scoped variables for these objects in your controller

wintry quarry
north kiln
#

why does the controller need to track these objects, when it should just be finding them when you click on them. It should only hold onto them for as long as they are being dragged, and nothing more.

wintry quarry
#

And it's causing issues

hoary mural
#

hey, I'm trying to make a pong clone in order to practice, and I'm wondering if I really should make two different player objects, or if I should make a parent object
which one would be better here?

rich adder
#

prefably 1 prefab

hoary mural
rich adder
robust stirrup
rich adder
# hoary mural oh alr, thanks!

this way when you apply changes into one prefab (eg changing movespeed and stuff/ change visual) you can easily just apply to the other player

rancid pollen
#

Hey, i am in the process of making a top-down(2D) tower defense game, and I have started with a tilemap for the ground and I want the specific tile to highlight when the mouse hovers on that tile, any tips on how to implement it ?

rich adder
#

by above i mean it has bigger number for **order in layer ** in tilemap renderer component

opal fossil
#

if i have a monobehaviour that inherits another, say Eagle inherits bird, and bird and eagle both have private void Awake(), would they both be called or would only the eagle's awake be called

north kiln
opal fossil
#

alright

rancid pollen
hardy lintel
#

https://hastebin.com/share/egugawesek.csharp
im having a bit of trouble with code i want to alter. i want to change my nodeui so it shows the tower/turrets stats at lvl2. i was able to make it so it changes for each specific turret. but i am struggling to do it for the upgraded variants. im sure i have added all relevant code files. any help is appreciated. thank you

timber tide
#
towerStats.text = target.turrentBlueprint.towerStat;```
#

when you change your tower, does the blueprint not change?

#

you should update the tower when you upgrade it with the new blueprint, or make a whole new tower that includes the blueprint,

willow nexus
timber tide
#

what

willow nexus
timber tide
#

Ah, may need to rasterize the navmesh with a smaller voxel size

#

and increase the height of which the agent can walk over

#

oh sorry im sleepy, I'm thinking you're doing a navmesh cause you got a minimap ;)

#

Unfortunately I've not used unity's rb and physics together much

frozen mantle
#

is it bad practice to use gameObject.SendMessage() to manually call OnTriggerEnter?

cosmic dagger
#

OnTriggerEnter is automatically called by the engine. you don't manually call it . . .

young warren
#

also, why must it be OnTriggerEnter?

#

cant you make your own function to call?

cosmic dagger
frozen mantle
cosmic dagger
# frozen mantle why come?

Using the SendMessage and BroadcastMessage functions is a bad convention in that they are very resource-intensive and difficult to debug. An alternative to these is calling methods directly via a reference or using a delegate/event setup

SendMessage has to go through every script, look for a method with the same name using string comparison (slower), and call it. The GetComponent finds the script through type comparison (faster) and calls the method directly. GetComponent can also be cached, which is the fastest alternative . . .

frozen mantle
#

Man

#

wack.

#

why can't this engine be good?

#

(im joking)

cosmic dagger
#

also, i believe SendMessage does not report errors when the method is incorrectly spelled since it uses strings . . .

young warren
#

the only reason you're facing difficulty now is lack of understanding of the available tools. i'd second learning to use a delegate/event setup, aka the Observer pattern

timber tide
#

no clue what sendmessage is but it throws errors on the editor when I create new meshes and I wish it would shush

young warren
frozen mantle
# young warren cant you make your own function to call?

yes but's that's a bitch in a half with my code base. Basically i have 8 different weapons in my game, that inherent from a "weaponBaseClass". the base class has a "shoot()" function that sends out the rayCast that checks what im hitting. the issue comes that 5 of my 8 weapons need to override this function to do their own special thing (like shotguns using a For() statement for it's pellet spread) and my explosive based weapons not using raycasts at all.) so if i wanted to add a new check for the "TargetTrigger" class, i need to go through 6 different scripts to add in the new check

young warren
#

what..?

#

so some use raycast, others use OnTriggerEnter?

#

to detect what they hit

frozen mantle
#

no no

young warren
#

probably easier if you showed the code

#

if you want help that is

frozen mantle
#

jeez louise

young warren
#

okay

frozen mantle
#

i got you, hold on

young warren
#

just show

#

i can wait

cosmic dagger
frozen mantle
#

this is my base Shoot() function

#

i know what i can do is just add in a new if statement for my TargetTrigger class like i have for Enemy and regular Target

#

but the issue is that i have 5 other weapons in my game that do not use the base Shoot() function, they have their own Shoot() functions

young warren
#

you keep mentioning this TargetTrigger class

#

why dont you show it

young warren
frozen mantle
#

that's my shoot function

young warren
#

okay

#

what's the issue with it?

#

i can see it uses raycast

#

so what's the problem you're facing now?

frozen mantle
#

so i would need to add the new if() statement for my new TargetTrigger class for all of them

young warren
#

you're getting ahead of yourself here

#

what's the issue with those shoot functions?

frozen mantle
#

and the issue if, what if i want to add another class that needs to be shot at and do something different?

young warren
#

what can't they do that you want them to do?

#

and how about you show some of those shoot functions? so we can see how they're different

#

and again, show your TargetTrigger class? it seems really important since you keep mentioning it

frozen mantle
#

This is all it does atm

young warren
#

okay

#

so what's the issue here? what would normally collide with this trigger?

frozen mantle
#

but now i know that rayCasts do not set off OnTriggerEnter

young warren
#

okay, do other Shoot functions do something that would trigger this OnTriggerEnter?

young warren
#

can you show those other Shoot functions please?

#

so why did you set up this OnTriggerEnter then?

frozen mantle
#

as i said

#

i thought rayCasts set off OnTriggerEnter

young warren
#

okay

frozen mantle
#

i now know they do not

young warren
#

then we can let go of the OnTriggerEnter

#

show the other Shoot functions please?

frozen mantle
#

yes i know that much

#

ok

young warren
#

is this TargetTrigger on the object that you're hitting with the raycast?

frozen mantle
#

gimme just a quick segundo

young warren
#

okay. i'll wait on those Shoot functions

#

so from what I can understand, the base Shoot function does these

  • spawns a bullet trail,
  • if you hit an enemy, the enemy takes damage.
  • if you hit a Target, the target takes damage.
  • if you hit a rigidbody, it applies a force
  • and it instantiates an impact effect.

is the TargetTrigger a Target or Enemy?

#

or is it a separate thing that doesnt take damage, just destroys itself

frozen mantle
young warren
#

i can see some duplicate code between the base and the overriding Shoot functions

frozen mantle
young warren
#

why wasnt the duplicate code just part of the base Shoot

#

then you just call base.Shoot() in the overriding Shoot functions

frozen mantle
#

for the sniper, its because of how my recoil system works

young warren
#

then you wouldnt have to add the if statement in all the Shoot functions, since it seems like it should only be in the base Shoot

frozen mantle
#

for the explosive weapons, they don't use Raycasts, they use an overlap sphere

young warren
#

I see

frozen mantle
#

for the shotguns i need loop over the ray case sent out for each pellet, as they have a spread

#

my issue is that, i need to add a Target Trigger check to all of them, which would be easy, but tedious, esp because what if i want to add more Triggers to be shot at that do different things, like spawn enemies?

young warren
#

yeah this does seem like an unfortunate code architecture situation

#

valid concern

frozen mantle
#

what im thinking of doing is to just add a generic case

#

basically, if im not hitting an Enemy or Target, then to just call the OnHit() function of whatever i hit

young warren
#

i'm afraid i dont have the time or experience to properly suggest a refactor

young warren
#

i have to go now. all the best

frozen mantle
#

thanks

#

i didn't mean to come off as mad btw

#

more so just exasperated i guess

frozen mantle
timber tide
#

Could also derive like a projectile class and just have shoot handle how they come out of the weapon

#

raycast is an odd one out though

short moss
#

Hi did anyone ever got this issue? When saving TerrainLayer assets, it looks pretty normal (texture appears on the layer.asset). But whenever I click on the play button, all my layer's textures are being reset. The layers still keeps other settings

timber tide
#

still can be a projectile though and do a conditional check

frozen mantle
#

so i still need to add in the if check to all my scripts, but it'll be the last thing i need to add for this project

#

i don't think im gonna add anymore shootables that aren't triggers

timber tide
#

Recoil and stuff here can also just be another function on all your guns which you can make virtual

#

such that you'd have a bunch of other virtual methods that shoot calls

#

Stuff like your explode is just a condition for when a projectile hits, so it doesn't necessarily need to be tied to a specific weapon, but rather you can have an onhit trigger method for projectiles that will call these extra methods.

#

Sniper hits -> look through onhit triggers -> Explode();
Shotgun pellet hits -> look through onhit triggers -> Explode();

#

I'd just chop up a lot of your functionality if you want to make it reusable and stick it into their own methods.

frozen mantle
#

true

timber tide
#

Because technically all weapons can have multiple projectiles, but the ones you want you can just change that 1 to a 5 and so on

frozen mantle
#

but im much too lazy to rewrite my weapons code so im just gonna do my idea

thorny wedge
#

hey, anyone knows how to make a piece of code repeat for specific time? I tried smth but it doesnt seem to work (unity editor has frozen)

frozen mantle
#

i don't follow this

topaz mortar
#

if I create a Monster class for which the only purpose is to store values for my monster for my Combat class
is there a point in making the Monster class values private? or can I just leave them public, since I need them in the Combat class?

timber tide
# frozen mantle wait wat

Where ever you register a hit, or if you have like some onDestroy method for projectiles, I was suggesting to tie some functionality to that if sphere casting seems odd for a shoot function.

thorny wedge
rich adder
eternal falconBOT
frozen mantle
thorny wedge
#
private void Dash()
    {
        if (Input.GetButtonDown("Dash"))
        {
            if (canDash == true)
            {
                rigid.gravityScale = 0f;

                StartCoroutine(doDash());

                while(canDash == true)
                {
                    if (sprite.flipX == false)
                    {
                        rigid.velocity = new Vector2(10, 0);
                    } else if (sprite.flipX == true)
                    {
                        rigid.velocity = new Vector2(-10, 0);
                    }
                }
                
            }
        }
    }

    private IEnumerator doDash()
    {
        yield return new WaitForSeconds(2f);
        canDash = false;
        rigid.gravityScale = 3f;
    }
oblique ginkgo
#

at least, it doesnt end before unity crashes

timber tide
rich adder
#

and check for certain time lapsed

thorny wedge
#

ty

frozen mantle
timber tide
#

what do you want raycasted that then needs ontrigger?

frozen mantle
# timber tide what do you want raycasted that then needs ontrigger?

what? sorry i don;t think i understand what your asking fully. all my ballisitic guns use a raycast to see what im hitting. what i wanted to do is to have that RayCast or overlapSphere set off the OnTriggerEnter of my targetTrigger and then activate whatever i wanted activated. I would find this useful as i don't have to add new if() checks in my weapons scripts everytime i make a new shootable

#

but, i think im fine with adding one more if() check that just calls a targetTrigger, and if i need to add a new shootable that does something else other than just open a door (like say, turn off the lights and spawns in a few enemies) i can just make it a child of targetTrigger with an overrided OnHit() function

timber tide
#

Not seeing any of this code... but if this is like some class where you're comparing layers/targets, you'd just give your weapon types an enum that points to a layer mask that they can hit.

frozen mantle
#

i don't think we're on the right page, thjat's my fault, im awful at explaining things

frozen mantle
#

But i learned that raycasts do not call or set off OnTriggerEnter for colliders that they hit

timber tide
#

as far as if statements go, I'd just use them even if they don't apply to the current weapon. Usually the idea is to take advantage of virtual methods, but if you can't minimize it to that, it's not that big of a deal.

frozen mantle
#

but anyways, i already implemented my idea and it seems to work, so i think i am vibin'

timber tide
#

Ah, alright. Anyway I'mma sleep. If you do want to refactor it all out throw me all of it so I could get an idea. But if you're fine with it all, just go with it ;p

frozen mantle
#

that will hopefully be ALOT cleaner than this project, lol

spice smelt
#

how do i fix that

rich adder
#

move the camera also not a code question

stoic pike
#

When i scale up the size of my screen all my gameobjects scale up with it but my text my buttons any canvas element doesnt scale up in size and doesnt move to the correct position of the scaled up screen

topaz mortar
#

I have a Monster class with several fields
Their only purpose is to be used in the Combat class
Is there a point to make them private? Or can I just leave them public so I can get & set them easily from the Combat script?

vital tangle
#

Hello

#

I need some help with a little code

topaz mortar
#

I think most ppl here use Visual Studio instead, at least it's easier to set up with Unity

timber tide
#

c++ has like the friend keyword, but I don't think that's a concept in c#

topaz mortar
#

doing monster.health just seemed better than monsterHealth, since there's quite a few monster variables
It seems cleaner

supple wasp
#

Does anyone know how I can make a code for getting on and off the car?

static cedar
#

Seems like it's because the types match. UnityChanThink

#

That's probably all there is to it. UnityChanThink

supple wasp
#

Can you help me how to create a code to get on and off a car?

timber tide
topaz mortar
#

we can help you debug your code if you have any

static cedar
#

Yeah looks like Visual Studio.

topaz mortar
frozen mantle
timber tide
#

Once I can get this damn code to compile

topaz mortar
#

like how is a private with a get & set different from just public?

#

unless you have to apply logic in those get & set methods, which I won't ever have to do for Monster

timber tide
#

it's just a concept which doesn't necessarily need to be enforced, but it's a good habit to have like adding comments

supple wasp
#

I don't even know how to create code anymore...

#

I haven't scheduled anything for 1 month now.

timber tide
#

to prevent your teammembers or whoever else touched your code in the future and decides they can access something they shouldn't and break your code

supple wasp
#

And since I forget things quickly

topaz mortar
supple wasp
topaz mortar
#

like I said, there is a lot of free content as well

static cedar
#

Did u try learning C# first? UnityChanThink

timber tide
static cedar
#

Coding is largely a problem solving thing. Imagine doing puzzles but the rules aren't explained to you.

static cedar
# topaz mortar unless you have to apply logic in those get & set methods, which I won't ever ha...

There's a pretty good reason (for me) why i use protected, internal, or private. They exist to answer the question of "Am i supposed to fiddle with that from here?"
They also stop flooding intelisense suggestions when i don't need to which i like.

Getter and setter break it down more by having their own security. Normally, get; private set; is common since the class wants to set something from that field but not any other classes outside but still need it to be accessible.

Another example using getter and private setter is this [field: SerializeField] public var Value { get; private set; }. Since you can't do serializefield with a readonly, this is as close you can get. The Value isn't meant to be set by anything other than in the inspector, only referenced by other classes so you want to make the set part private. There's no higher security than private so the class that owns it can still set it though. UnityChanThink

By default, try making them private and if you know that they need to be accessible outside the class, make them public, see how that goes. UnityChanThink

topaz mortar
#

yeah that's pretty much what I've been doing

supple wasp
#

Accelerate and everything but it doesn't turn

north kiln
#

!code

eternal falconBOT
naive lion
#

can anyone explain switch statements to me and how they can be utilised

cloud flume
#

does anyone know why the enemy isnt moving towards the player? its like its being constantly teleported back, as shown in the video when i disable the animator i can move the enemy, pls help i dont know whats happening been stuck on this for ages

oblique ginkgo
#

i havent watched the video yet but are you forcing position with your animations

cloud flume
#

wdum

oblique ginkgo
#

you're moving the "ant" gameobject, right

cloud flume
#

well yeah, the script is attached to the ant and im just increasing its speed when player goes near it in the players direction

north kiln
#

Are the values set correctly in the Enemy inspector?

oblique ginkgo
#

so the problem is definitely animation if when you disable the animator it moves alright
is your animation overriding the "ant" gameobjects position?

cloud flume
#

yeah the problem is animation i know i just dont know what exactly

north kiln
#

Yeah, that's true, I usually set up the animated object as a child so it doesn't override the rigidibody

cloud flume
short hazel
#

Yeah the issue is that your animation is on the root object, and there are position keyframes so it applies the position of the animation

#

Usually, the object you animate is a child of the object you move

cloud flume
oblique ginkgo
#

You can probably just make a new gameobject, make "Ant" a child of it and put all your enemy logic on that parent

short hazel
#

You might need to reference the Animator again from the movment script, since it changed

cloud flume
short hazel
#

Yes, you can use the options menu of the components (three dots icon top-right) to copy and paste the components values

short hazel
#

Click > Copy Component on old object, Click > Paste Component As New on new object

cloud flume
#

thanks everyone that helped it worked, i was literally having such a hard time figuring that out!

hollow zephyr
#

Best way of having instant acceleration on a player movement script for 3D.

fossil sphinx
#

hi i just finished my top down movement code for animating both walk and idle but when i stop moving it stop on idle_down animation not on the idle animation that corespond with the axis it was previous on

modest dust
#

Can't say much without seeing the animator.

verbal dome
#

Fun tip, you can write that log
Debug.Log(animator.GetFloat("PosX") + ", " + animator.GetFloat("PosY"))
as
Debug.Log((animator.GetFloat("PosX"), animator.GetFloat("PosY")) and it will print out with the comma

#

Tuples are handy

#

Not that it really matters, just a little quality-of-life thing I started using recently

calm osprey
#

does anyone understand why the instantiate brackets don't have a space for size?

#

like i can control where it spawns and in what rotation, why can't i add a place for what size I want it to spawn at

languid spire
#

because scale is not relevant to all objects you can instantiate

calm osprey
#

so how do i control the size of stuff that I spawn

languid spire
#

apply it to the instantiated object

calm osprey
#

oh i guess that would work for me since I always want it to be in random sizes

#

but what if I only wanted the random sizes to exist on the instantiated objects, and wanted to keep the original prefab without random sizes

#

do i just duplicate and use them differently

languid spire
#

that is why I said 'instantiated object'

calm osprey
#

oh

#

how do i apply it tho if the instantiate function doesnt have space for it

static cedar
#

Space? UnityChanThink

calm osprey
#

im reading the instantiate documentation and there's no area for scale

languid spire
#
object instantiatedObject = Instantiate(prefab...);
calm osprey
#

i already have the code with the position and rotation filled in but the documentation only shows I can add "parent" and "instantiateInWorldSpace" which don't seem to be what i'm looking for

sour fulcrum
#

just apply position on the next line of code homie

languid spire
#
object instantiatedObject = Instantiate(prefab...);
instantiatedObject.localScale = new Vector3(...);
calm osprey
#

ok I think I wrote it correctly but it doesn't recognize "instantiatedObject"

languid spire
#

show code

calm osprey
#

how to I reference to it

#

the object's prefab is called "Baddie"

#

so far it spawned from right to left on a random Y position, so I wanted to add scale randomness

languid spire
#

and how does your instantiate look like this?

object instantiatedObject = Instantiate(prefab...);
calm osprey
#

idk how it looks

#

is my instantiate not on this screenshot?

#

lmao Im sorry i started today

languid spire
#

yes, and it looks nothing like mine

sour fulcrum
#

needs to be GameObject

languid spire
#

@calm osprey also post code correctly
!code

eternal falconBOT
calm osprey
#
// Your code herepublic class BaddieSpawner : MonoBehaviour
{
    public GameObject Baddie;
    public float spawnRate = 2;
    private float timer = 0;
    public float heightOffset = 7;
    public float scaleOffset = 2;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (timer < spawnRate)
        {
            timer = timer + Time.deltaTime;
        }
        else
        {
            float smallestSizeX = transform.localScale.x - scaleOffset;
            float biggestSizeX = transform.localScale.x + scaleOffset;
            float smallestSizeY = transform.localScale.y - scaleOffset;
            float biggestSizeY = transform.localScale.y + scaleOffset;

            float lowestPoint = transform.position.y - heightOffset;
            float highestPoint = transform.position.y + heightOffset;

            Instantiate(Baddie, new Vector3(transform.position.x, Random.Range(lowestPoint, highestPoint), 0), transform.rotation);
            instantiatedObject.localScale = new Vector3(Random.Range(smallestSizeX, biggestSizeX), Random.Range(smallestSizeY, biggestSizeY));
            
            timer = 0;
        }


    }
languid spire
calm osprey
#

my instantiate is for the position tho

languid spire
#

yes, but I'm trying not to spoonfeed

north kiln
#

Probably worth using var in examples, not object

sour fulcrum
#

spawn the object

#

change the object size*

#

two steps

languid spire
calm osprey
#

so I need to create another gameObject for the instantiated objects?

#

and then I can reference it in the "instantiatedObject" line to make it scale?

#

because the position code works

north kiln
golden ermine
#

Guys I have my custom cursor set as you can see in image and it works when i click play in Unity but when I build the game its normal mouse cursor...do I need to have some kind of script for it to work when game is built or?

oak imp
#

Hey, anyone know if a disabled unity script can still utilize static variables of a class?

verbal dome
#

Other than that, the code will work normally

swift crag
#

yes -- there's no "magic"

#

you can still call methods on the object and use fields from the object

#

even destroying a unity object doesn't stop you from doing that (you'll just get errors if you try to use Unity methods/properties)

oak imp
#

Its like a string typed null too which just adds more to my confusion. lol.

swift crag
#

strings can be null. they're reference types.

#

show your code

uncut dune
#

is it better to use properties instead of fields everytime we want to access them from other scripts?

oak imp
#

its from a very large chunk of code. I don't expect to find a solution this way but if you want a shot... here:

subtle veldt
#

Hey most people seems to use this code to move a player in a 2D platformer game :

    void Update()
    {
        playerRigidbody.velocity = new Vector2(inputX * walkingSpeed, playerRigidbody.velocity.y);
    }

    public void Move(InputAction.CallbackContext context)
    {
        inputX = context.ReadValue<Vector2>().x;
    }

But I can't use this because it doesn't seem to work well with SpringJoints2D. When my player is connected to another object with a SpringJoint2D, the physics break. I don't know how to fix that.

oak imp
subtle veldt
#

No physics work fine but when I enable the spring joint it's doing weird things. And I tried without the movement code and it works fine

swift crag
eternal falconBOT
robust stirrup
swift crag
#

so, what is the problem?

oak imp
# swift crag so, what is the problem?

On the static public variable Grid. Once a piece becomes gravity disabled. Instead of the piece appearing on the grid i get a value of "null" from the debuger.

#

And thats with the quotes.

swift crag
#

you set grid elements to null in several places

oak imp
#

Yes. But that should only be if tags match and have an appropriate top and bottom

#

In the debugger does a new null appear as "null" ?

final kestrel
#

Guys this is what my gameplay looks like. Along with the character control script https://hatebin.com/wcpmpalgah.
The jumping feels so off. I tried changing jump force, then damping then gravity. It just does not feel like jumping. I want it to jump in an arc but it just goes up and down almost in a straight line.

swift crag
verbal dome
#

Does it have drag?

#

@final kestrel

final kestrel
#

Yes the settings are like this right now

swift crag
#

that drag is pretty massive

oak imp
verbal dome
#

I notice the drag in the video

swift crag
#

also, your paste is off by at least one line (you put ```cs on the first line). You'll need to copy the line that you're talking about.

oak imp
swift crag
#

Ah.

#

I believe you see "null" everywhere when looking at a destroyed unity object

final kestrel
#

I increase the move speed then the jump is just like i want but then I move too fast.

robust stirrup
oak imp
#

Oh! that kinda makes sense. But its sprite is still rendered.

verbal dome
#

Thats what makes you fall down vertically

#

Because at that point the jump force is totally drag'd and you only get gravity

#

Hmm

final kestrel
#

Okay I made the drag 1. I get slightly higher air time

verbal dome
#

You can always change the drag depending on if youre walking or jumping too

final kestrel
#

but again. Is there any way to like make it feel like im actually leaping forward

verbal dome
#

Less y force, more xz force

final kestrel
#

so increase move speed and decrease jump force?

verbal dome
#

I mean make the X and Z of the jump force larger

#

Actually idk even how your jumping works

#

Do you even add horizontal force when jumping? Or just vertical/y?

verbal dome
#

Ah you posted code

swift crag
#

you're constantly setting your X and Z velocity

#

so you won't be able to make a jump that "leaps forward" without changing that

verbal dome
#

Yep. You could handle the movement differently when you are in a jumping/falling state

#

For example, with AddForce instead of the current rb.velocity =...

final kestrel
#

Add force prevents me from making sharp turns though

#

Thats why I set the velocity

verbal dome
#

Do you need sharp turns in the air?

final kestrel
#

No not in the air.

oak imp
#

@swift crag ! Thank you! I figured it out! After destroying an intermidiary piece for ice cream, destroying part of it made it appear as "null" on the grid. Thanks for your help!

swift crag
#

That'll do it -- destroyed unity objects will compare equal to null

verbal dome
final kestrel
#

Oh you mean when I jump, I use add force in the air for forward movement?

#

Aah

verbal dome
#

Yeah

final kestrel
#

What do I change though

#

I am kind of confused sorry

verbal dome
#

Make a variable that tracks if you are on the ground or not

#

Maybe you already got that

final kestrel
#

I have a ground check object

verbal dome
#

If grounded, use rb.velocity.
If not, use addforce

final kestrel
#

hmm

#

Okay I will try. Thanks

verbal dome
#

(Bonus: read about 'coyote time')

final kestrel
#

coyote time helps me jump after missing the platform a bit though no?

#

How are they related

verbal dome
#

Yeah that

final kestrel
#

Just asking dont get me wrong.

verbal dome
#

It might become relevant, but forget it for now

final kestrel
#

All right thanks a lot.

subtle veldt
#

Sorry but does anyone have an idea on how to solve my problem ? I can't find anything

swift crag
wintry quarry
wintry quarry
robust stirrup
wintry quarry
subtle veldt
robust stirrup
#

I'll remove 0.20.3

wintry quarry
verbal dome
edgy timber
#

float runSpeed = 10f;

edgy timber
#

why do u have to type f at end when it is already declared to be of float type?

wintry quarry
verbal dome
#

If it was 'var' then yes

#

It just needs some clue that it is a float

edgy timber
#

so how does this help?

wintry quarry
edgy timber
#

limit the number of decimals?

subtle veldt
wintry quarry
edgy timber
#

got that

wintry quarry
#

5 is an int literal which is implicitly converted to float

#

Double cannot be implicitly converted to float

blissful trail
#

anyone have any idea why the last 2 events on my animation arent triggering?

wintry quarry
#

You must use a float literal instead, hence the f

verbal dome
wintry quarry
edgy timber
subtle veldt
blissful trail
#

so i dont think they should

edgy timber
#

Vector2 playerVelocity = new Vector2(moveInput.x, 0f);

wintry quarry
edgy timber
#

in this case how does the f help here?

wintry quarry
blissful trail
#

why would you need a double as opposed to a float? just curious

blissful trail
verbal dome
blissful trail
#

the last frames in the animation are running too

wintry quarry
blissful trail
#

is that what the little grey end segment is?

wintry quarry
#

Yes

#

That's the part that won't play

blissful trail
#

I see

#

that should be the problem then

#

thank you very much praetor

#

yep that solved it : )

prime oar
#

Um, how do you make it, so the whole map is dark, and the units have a light within a radius of them? I can't find a tutorial.

#

I heard it's called fog of war but I don't want to memorize the pathway and making it lit up too

#

Just the units and everything that is within a radius of it

#

Like this

#

and without memorizing pathway

bitter carbon
#

Image
im tryna make array, am i missing something

polar acorn
wintry quarry
#

Also you can't use a field as the size like that

polar acorn
# bitter carbon

You cannot use a field to initialize another field. Create that array inside a function instead

wintry quarry
#

Not in the initializer

bitter carbon
wintry quarry
#

Values go in {}, check some examples

#

Also as mentioned above you can't use the field in it in the field initializer

#

It would have to go in Awake

short hazel
#

= new int[] { minTime, maxTime };

#

If you put it in the square brackets, it denotes the length of the array, which is not what you want

prime oar
#

anyone 😞

short hazel
#

!collab

eternal falconBOT
polar acorn
#

Maybe if the contract is smart enough it'll be able to find your missing capslock key

stiff stump
#

can a raycast be shaped more like a cone for an enemy field of view?

frosty hound
#

No, a ray is a laser, it has no shape.

#

You can use an overlap sphere to determine what is within a certain radius of the player, then filter them out based on angle from the players forward direction.

polar acorn
stiff stump
#

okay. how would i check if the player is within a angle of ths circle overlap?

frosty hound
#

To determine the angle between the players forward direction and the direction to the object you're checking.

idle lance
#

how do I make a table?

#

to store information of multiple variables

ashen ferry
#

arrays lists etc we aint got no tables kekW

summer stump
#

But I question whether you need a table for your use case. You could just make a struct or a POCO 🤷‍♂️

swift crag
#

or a dictionary, or a list

#

more information is required

idle lance
#

I'm trying to create a simulation

#

similar to those evolution simulation things but instead for economics

idle lance
swift crag
#

Explain what kind of data you are trying to store.

#

So far you have said "How do I store multiple things?"

eager elm
#

I don't think he knows that yet either

swift crag
#

If you want to store many copies of something in order, use List<T>. If you want to associate keys with values, use Dictionary<K,V>.

idle lance
#

every index on the table has code run for it

swift crag
#

okay, so you're going to have a list of actors

idle lance
#

yes

swift crag
#

so at the top level you'll have List<Actor>

#

and an Actor could have some variables in it for internal state

idle lance
#

ok

#

ill look up how to use lists

gleaming wagon
#

I have this error I got, after adding some packed gameobjects to the inspector of a script and deleting them from the scene, any way I can fix this without having to add them to the scene?

swift crag
#

well, your Outline script is trying to modify the UVs of a mesh

#

but the mesh is not marked read/write

#

sounds like that's your problem

gleaming wagon
#

How do i fix that tho?

swift crag
#

find the mesh in your Project folder and check "Read/Write Enabled" in the inspector

#

this keeps a copy of the mesh data in memory

#

instead of just uploading it to the GPU and forgetting about it

gleaming wagon
#

Okay thanks

swift crag
#

are you talking about prefabs?

gleaming wagon
#

Yeah, basically I have a script which spawns ore when you mine, but I dont want to have the ores in the scene already so i packed them into a prefab. And then added them to the script whioch spawns the ores

swift crag
#

The error is unrelated to whether or not the objects are prefabs.

gleaming wagon
#

I know, it's just i want them to be prefabs since they have scripts etc. Btw ur read/write thingy worked

idle lance
#

lists only let me assign one variable

swift crag
#

well, Actor would be a whole class

#
public class Actor {
  public float happiness;
  public float timeSinceLastAction;
}
#

e.g.

idle lance
#

ohhh

#

ok

swift crag
#

If you want some actors to store data that other actors don't, you might want to make more classes that derive from Actor

idle lance
#

ok yeah I get it

#

thank you!!!

swift crag
#

Or you might want something composition-based, where actors, themselves, have a list of modules/components

idle lance
swift crag
#

it sounds like you need to do some introductory C# tutorials

#

these are really fundamental concepts

#

the C# docs have some nice tutorials, and Unity Learn has pathways for learning about scripting in the context of Unity

idle lance
#

ok cool

turbid robin
#

is there a way to add collision to some of this tileset object?

#

fot the moment i added 2 2d box collider

#

but i dont think its the best idea because i need to do it every time

rich adder
turbid robin
rich adder
turbid robin
turbid robin
rich adder
#

one with collider and one without

turbid robin
#

oh,its the only way?

rich adder
#

no other way that I know of 🤷‍♂️

turbid robin
#

sad, that not the best

#

i dont know how to create a tile map, i searched it online

rich adder
#

you get used to it

turbid robin
barren vapor
turbid robin
turbid robin
rich adder
#

spritesheet?

turbid robin
#

like this^^

rich adder
#

remember the grid size (8x8?)

turbid robin
queen adder
#

just realissed my question may have been better asked in the cinemachine fourm so have removed it to there, sorry 😛

rich adder
turbid robin
#

i need to create it

rich adder
turbid robin
#

i found it on google

#

i have to create it with my sprite

#

i have a lot of sprites but not only 1 image

rich adder
#

you slice. it

#

thats wht a sprite sheet is for

turbid robin
#

i dont remember that in the tutorial

rich adder
#

set the spritemode to Multiple

#

then use sprite editor

#

click slice by grid size and do 8 x 8 if thats the size

turbid robin
#

ok

rich adder
#

you did it wrong

turbid robin
#

no no i fixed

uncut dune
#

how to remove from a list from a specific index

#

like deleting that specific index

short hazel
#

list.RemoveAt(index)

uncut dune
short hazel
#

Complete removal

uncut dune
#

good

#

thank you

buoyant knot
#

Let's say I have two lists, one List<GameObject> and List<Collider2D>, and I want to sort both by the same Func<List<GameObject>, List<GameObject>>, but i want it to basically look into the collider2D's gameobject field/property for the sorting. Is there a clean way to define one method to do it all?

sand glen
#

Custom wrapper?

buoyant knot
#

I'm trying to use Linq's: x => x.OrderBy().ThenBy().ThenBy(), to define that function

#

maybe I could use an IComparer instead?

#

since I just have a few specific sorts I plan on doing a lot

#

maybe Comparison<GameObject>?

ripe shard
#

why not order them separately?

#

or do you want to merge them?

swift stag
#

Does anyone know what this error means? Graphics.CopyTexture called for entire mipmaps with different memory size (source (RGBA8 UNorm) is 1024 bytes and destination (Alpha8 UNorm) is 256 bytes)
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)

buoyant knot
#

not merge

#

I will likely need to define a function that:

  1. looks up each gameobject in a dictionary to get a different class
  2. compare field 1 of that other object
  3. if tie, compare field 2
  4. if tie, compare field 3
#

but idk the most performant way to do this

#

nor generic way to do this

ripe shard
#

are the sort fields all comparable?

wintry quarry
ripe shard
#

i.e. are they all primitive values of comparable types?

gaunt ice
#

your comparer needs to reference to something other than the two arguments, i will make a new comparer class implements IComparer<T>.....

buoyant knot
#

ITreeChild is only implemented by monobehaviours, and ITreeChild has a .gameObject property. Not all nodes have a monobehaviour implementing a common interface.

wintry quarry
#

why isn't it just a Dictionary<ITreeChild, List<ITreeChild>>

#

generally in a tree structure you treat all nodes pretty agnostically

buoyant knot
#

because root nodes might not have an ITreeChild

wintry quarry
#

They... should

#

They should be ITreeNode really

buoyant knot
#

perhaps that might be better

wintry quarry
#

also a tree only generally has a single root

gaunt ice
#

root is still tree node

wintry quarry
#

so if you have a list of roots

#

that's kind of multiple trees

buoyant knot
#

the class is a collection of trees, yes

#

because every time I delete something in the middle, I want to define everything below it as its own separate tree, if that makes sense

wintry quarry
buoyant knot
#

that might be the better way

gaunt ice
#

you cant distinguish root from "normal tree node" since each node can be the root of its subtree

wintry quarry
#

like:

void DeleteNode(ITreeNode node) {
  foreach (ITreeNode child in node.Children) {
    child.parent = null;
    roots.Add(child); // each child becomes its own tree
  }

  if (node.parent != null) node.parent.Children.Remove(node);
}``` as a quick pseudocode
buoyant knot
#

delete node is a lot more involved, tbh. Because we need to know if we have children, and if we have children, move them all to be root nodes. And also remove the node to be deleted as a dependent of anything it is a dependent of.

wintry quarry
#

it covers all of that

#

this is relying on a .parent reference which might be a good idea too

buoyant knot
#

I might be able to refactor. The thing I need to wrestle with is some objects allowing themselves to only be a child, to only be a parent, and some allow both

wintry quarry
#

do you just throw the child away?

#

anyway you can add:

public bool CanBeParent { get; }
public bool CanbeChild { get; }``` to the ITreeNode interface
#

and handle that as needed

buoyant knot
#

in that scenario, we need to check if child has dependents. if child has no children of its own, delete from tree. Else, promote it to a root

#

that's part of what makes this structure kind of involved to manage

ripe shard
#

a root is just a node with no parent

ebon sapphire
#

healthBar:
using UnityEngine;
using UnityEngine.UI;

public class HealthBar : MonoBehaviour
{
public Image healthBar;
public float healthAmount = 100f;

void Update()
{
    // Check for the "Return" key press
    if (Input.GetKeyDown(KeyCode.Return))
    {
        TakeDamage(10); // Apply damage to the player's health when "Return" key is pressed
    }
}

public void TakeDamage(float damage)
{
    healthAmount -= damage;
    healthAmount = Mathf.Clamp(healthAmount, 0, 100); // Ensure health doesn't go below 0
    healthBar.fillAmount = healthAmount / 100f;

    // You can remove the knockback signal to the player here
}

}

PlayerMovement:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
public float moveSpeed = 5f;
public Animator animator;
public float StandStillSpeed = 0.1f;
public HealthBar healthBar; // Reference to the HealthBar script

private Rigidbody2D rb;

private void Start()
{
    rb = GetComponent<Rigidbody2D>();
}

private void Update()
{
    // Get input for movement in the x and y axes.
    float moveX = Input.GetAxis("Horizontal");
    float moveY = Input.GetAxis("Vertical");

    animator.SetFloat("SpeedX", moveX);
    animator.SetFloat("SpeedY", moveY);
    if (moveX > StandStillSpeed || -moveX > StandStillSpeed || moveY > StandStillSpeed || -moveY > StandStillSpeed)
    {
        animator.SetBool("Still", false);
    }
    else
    {
        animator.SetBool("Still", true);
    }

    // Calculate the movement vector.
    Vector2 moveDirection = new Vector2(moveX, moveY).normalized;

    // Apply the movement.
    rb.velocity = moveDirection * moveSpeed;
}

private void OnTriggerEnter2D(Collider2D collider)
{
    Debug.Log("TRIGGER");
}

}

short hazel
#

!code

eternal falconBOT
short hazel
#

Hm actually use a paste site, it's not small

buoyant knot
#

I see now that was a mistake.

short hazel
#

You can make a node generic, so you're able to make trees of anything

#

class Node<T>

hidden bone
#

Can I get some help with reading contents from a .txt file and displaying it in an inputfield?

gaunt ice
#

fileIO

desert flume
#

uh quick question, is this how a script is supposed to look? it looks grayed out so i assume something's wrong

summer stump
#

In the console

Or did you change the name of the script?

hidden bone
rich adder
#

unless you got compiler errors lol

desert flume
#

stuff got messy im gonna make a new project lol

#

first time using unity

rich adder
desert flume
#

where do i right click

rich adder
desert flume
#

now what

#

its empty now

rich adder
desert flume
#

yeah ok i have no idea how unity works

rich adder
#

is the script still missing the label /header?

desert flume
#

where is the script now

rich adder
#

what?

#

the same thinig you did before

summer stump
desert flume
rich adder
#

this? did you check it

summer stump
#

And the script would be in the project window

desert flume
#

it doesnt auto save?

summer stump
desert flume
rich adder
#

ok so its fixed..

#

2022 unity strikes again

desert flume
#

yeah so uh

#

how do i learn to use unity lol

rich adder
#

no go some unity essentials

#

!learn

eternal falconBOT
#

:teacher: Unity Learn

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

desert flume
#

i already know how to code

#

if that helps

rich adder
#

start with Unity Essentials first

astral basin
#

this is my script, when i change jumpForce the player doesnt jump any higher, but when i set the maxSpeed to higher values. the jump is also higher, any idea how to fix? thanks

buoyant knot
#

is your rigidbody set to dynamic?

wintry quarry
astral basin
buoyant knot
#

i just had to check first

astral basin
buoyant knot
#

maxspeed operates on all of velocity, not just the X

wintry quarry
#

it's never correct to use deltaTime with AddForce

astral basin
#

oky

#

will do

wintry quarry
#

you will probably need to reduce your force values somewhat

astral basin
buoyant knot
#

i would calculate jumpforce/jumpspeed by jump height

wintry quarry
#

but yeah honestly not seeing anything in the code that would cause the described issue with jump height

buoyant knot
#

in the fixed update

wintry quarry
#

they're comparing velocity.x to the max speed

astral basin
#

so move the jump into the fixedupdte too?

wintry quarry
#

not the whole magnitude

buoyant knot
#

maxspeed should not fuck with Y velocity at all

#

do you need help calculating jump force from jump height?

astral basin
#

whats the difference between those

#

could this be the issue?if so how do i compre velocity.x.magnitude to maxSpeed

wintry quarry
#

instead of magnitude

astral basin
#

let metry

wintry quarry
#

but

#

there's more

astral basin
#

?

wintry quarry
#

the line inside would have to be:

Vector3 velocity = rb.velocity;
velocity.x = maxSpeed;
rb.velocity = velocity;```
glad igloo
#

I just started coding on unity and it my code doesnt seem to work even though i followed a tutorial can anyone help, maybe my version of visual studio is old or something

buoyant knot
#

This code should help you. You should stick it in at some point:

gravityStrength = -(2 * jumpHeight) / (jumpTimeToApex * jumpTimeToApex);
//Calculate the rigidbody's gravity scale (ie: gravity strength relative to unity's gravity value, see project settings/Physics2D). Assign this value to the rigidbody
gravityScale = gravityStrength / Physics2D.gravity.y;
// Calculate forces. impulse force is more like velocity. Use vf^2 = vi^2 + 2a*dist
jumpForce = Mathf.Sqrt(Mathf.Abs(gravityStrength * 2 * jumpHeight));```
glad igloo
wintry quarry
#

you have compile errors

wintry quarry
#

!vs

eternal falconBOT
#
Visual Studio guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

glad igloo
wintry quarry
astral basin
buoyant knot
astral basin
buoyant knot
#

the code I gave you takes in a desired jump height AND desired time (in seconds) until you hit the top of your jump arc. And it calculates for you the gravity scale you need to set on your RB and jump force you need to use to make it happen

#

changing jump height by playing with a value of force in units * units / s^2 is suck

astral basin
#

do i need to set those as variables or am i missing a directory

buoyant knot
#

you need to define them

#

jumpTimeToApex and jumpHeight are both floats

#

these are the two numbers you serialize

#

gravity scale can be directly fed into rigidbody.gravity

#

jumpForce is the variable you're using, but you no longer need to define it in inspector. We are overwriting it to make the jump height and hangtime match

#

does this make sense?

astral basin
#

kind of

buoyant knot
#

and also, you need to use rigidbody.AddForce(jumpForce, ForceMode.Impulse)

#

Impulse mode applies all the force at once, as though we are changing velocity

astral basin
#

i used impluse mode when writing the addforce

#

what do i do with the gravity strength

#

what is it

buoyant knot
#

ok that's good

#

gravityStrength is a float. We don't need to store long term. We just want to hold it for that calculation because it is gravitational accelleration in units/s^2

astral basin
#

alright

buoyant knot
#

make sense?

astral basin
#

yes

#

so when i modifty the gravity scale according to it, it applies the time and jump height

buoyant knot
#

the point of what I'm telling you is not to fix your problem, but to let you express how your jump works in terms of time and jump height, which are a lot more intuitive to work wit

astral basin
#

its just a different way to modify the jump

buoyant knot
#

yeah, so what unity does is it has Physics2D.gravity, which is a vector for gravitational acceleration

#

rigidbody2D has a gravityScale property that multiplies gravity by that much for just that one rigidbody

#

your RigidBody2D basically always has rb.AddForce(rb.mass * rb.gravityScale * Physics2D.gravity) every single frame

#

the gravity scale and force are both calculated to hit both height/time requested.

#

anyway, I think I went overboard. good luck

astral basin
#

i understand, the way it works is really cool, thanks for your help, probably gonna use that in other projects too

buoyant knot
#

sure. I recommend brushing up on basic kinematic physics if you are rusty. It’s extremely useful

#

unity mostly tries to obey classical Newtonian physics

alpine mortar
#

Hey, I have a problem where When I change scene from the options scene to the main menu scene, the brightness (its just a panel that changes its opacity) works, but when I go back to options, it gets darker.

rich adder
alpine mortar
#

yeah

#

lemme upload a screenshot rq

rich adder
#

should probably show the script you're using for that

#

no screenshots

#

!code

eternal falconBOT
alpine mortar
#

okok

#

!code

eternal falconBOT
rich adder
#

oof

#

you're supposed to read it

#

and use links

alpine mortar
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class BrightnessManager : MonoBehaviour
{
    public Slider slider;
    public float sliderValue;
    public Image panelBrillo;

    // Start is called before the first frame update
    void Start()
    {
        slider.value = PlayerPrefs.GetFloat("brillo", 0.5f);

        panelBrillo.color = new Color(panelBrillo.color.r, panelBrillo.color.g, panelBrillo.color.b, slider.value);
    }

    //Update is called once per frame
    void Update()
    {

    }

    public void ChangeSlider(float valor)
    {
        sliderValue = valor;
        PlayerPrefs.SetFloat("brillo", sliderValue);
        panelBrillo.color = new Color(panelBrillo.color.r, panelBrillo.color.g, panelBrillo.color.b, slider.value);
    }
}
#

got it

#

a slider changes the alpha value of the panel

rich adder
#

from the video it looks like your slider starts changing something else

#

show the inspector for slider @alpine mortar

alpine mortar
rich adder
#

are you deactivating that gameobject ?

alpine mortar
#

no

#

I think

#

in theory this is the object

rich adder
#

I see whats going on

#

you keep spawning some type of panel on top

alpine mortar
#

yes

rich adder
#

InBetweenScenes

alpine mortar
#

exactly

rich adder
#

why

alpine mortar
#

to change the brightness

rich adder
#

...

#

why not just change alpha on 1 image

alpine mortar
#

idk man I started learning today

#

idk how

rich adder
#

also for this you would use post processing

#

but anyway the code you showed is not really important, the one you spawn BetweenScenes stuff is

alpine mortar
#

wait a sec

#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class Persistent : MonoBehaviour
{
    public GameObject panelBrightness;

    private void Awake()
    {
        DontDestroyOnLoad(gameObject);
    }

    private void OnEnable()
    {
        SceneManager.sceneLoaded += OnSceneLoaded;
    }

    private void OnDisable()
    {
        SceneManager.sceneLoaded -= OnSceneLoaded;
    }

    private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
    {
        if (scene.name == "MainMenu")
        {
            
            if (panelBrightness != null)
            {
                panelBrightness.SetActive(true);
              
            }
        }
    }
}
grizzled acorn
#

I want to make a game where you can stack blocks (kinda like tetris) but as soon as they touch each other, they get "glued" together and don't move relative to each other I want to however have the tower tip over if it's unbalanced. How can I achieve this?

alpine mortar
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class ChangeScenes : MonoBehaviour
{
    public void Play()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 2);
    }
    public void Options()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
    }
    public void Quit()
    {
        Application.Quit();
        Debug.Log("Player has quit the game");
    }
    public void BackToMainMenu()
    {
        SceneManager.LoadScene(0);
    }
    public GameObject OptionsMenu;
    public void ActivateObject()
    {
        OptionsMenu.SetActive(false);
    }
}

#

I ain't got more code

grizzled acorn
#

Wdym?

rich adder
sleek lichen
#

Hallo, I'm trying to rotate an object and read it's x rotation value using transform.eulerAngles.x, but as it rotates from 0 to 360 degrees it's returning 0, 45, 90, 45, 0 for the 0-180 range and 360, 315, 270, 315, and 360 for the 180-360 range. can someone please help me find how to get it to be 0-360?

rich adder
alpine mortar
#

ok

rich adder
#

this whole system is flawed

#

just use post processing

#

i have no idea why you even added DontDestroyOnLoad(gameObject);

alpine mortar
#

because if I change scenes the panel disappears

#

and with this it doesn't

rich adder
#

break one thing to fix another

alpine mortar
#

ok

#

just delete everything brightness related

rich adder
rich adder
grizzled acorn
alpine mortar
rich adder
#

I said use Joint/ possibly fixed joint

#

then youwoudl typically llook into it

#

or just ask about what ur confused on lol

strong wren
#

For a proper glue I would probably try removing the RB of the new cube and parenting it to the stack

rich adder
#

oh yeah true, it could all just be 1 rigidbody with several colliders

rich adder
rich adder
alpine mortar
#

thanks

warm raptor
#

hello I have a little problem with my shooting system in my multiplayer, in fact when I'm shooting I made a script to detect the colision between the ennemy and the bullet and if it detect a hit, the ennemy return hit in the console, but as you can see when i'm shooting the ennemy it don't return every time hit and it's a big problem. I think i have this issue because the amo is too fast and it go threw the player because it so fast that between 2 positions it didnt even detect that he go threw the player. do you know how I can fix this issue without reducing the speed of my bullet?

the ennemy code that detect if it has been hit:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Ennemie : MonoBehaviour
{
    private float MyID;
    private float X;
    private float Y;
    private float Z;
    private float YRot;

    void Start()
    {    
    while (MyID==0)
    {
            MyID = GameObject.Find("Player").GetComponent<CLIENT>().NewID;
            Debug.Log("PlayerID is : " + MyID);
    }
    }

    void Update()
    {
    if (GameObject.Find("Player").GetComponent<CLIENT>().NewID==MyID)
    {
        X = GameObject.Find("Player").GetComponent<CLIENT>().XValue;
        Y = GameObject.Find("Player").GetComponent<CLIENT>().YValue;
        Z = GameObject.Find("Player").GetComponent<CLIENT>().ZValue;
        YRot = GameObject.Find("Player").GetComponent<CLIENT>().YRot;
    }
    Vector3 CurrentPos = new Vector3(X, Y, Z);
        transform.position = CurrentPos;
    Vector3 CurrentRotation = new Vector3(0, YRot, 0);
        transform.eulerAngles = CurrentRotation;
    if (GameObject.Find("Player").GetComponent<CLIENT>().DisconectedID==MyID)
    {    
        Destroy(gameObject);
    }    
    }   
    void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.CompareTag("Bullet"))
        {
        Debug.Log("Hit");
    }
    }   
}

(sorry for my terrible english)

rich adder
#

oh...lordy..

#

please don't start with multiplayer when you're a beginner

#

this is beyond cursed GameObject.Find("Player").GetComponent<CLIENT>().XValue;

glad igloo
#

Can anyone check my code quickly because my playeris supposed to be able to jump around multiple times but it only jumps once and thats it

rich adder
#

while (MyID==0)
{
MyID = GameObject.Find("Player").GetComponent<CLIENT>().NewID;
Debug.Log("PlayerID is : " + MyID);
}
😵‍💫

rich adder
#

where do people get this code from

#

third time i've seen this curse

glad igloo
#

seriously damnnn😢 but i got it from a tutorial on youtube from the GameCodeLibrary

rich adder
#

its a bad tutorial

#

try this one

glad igloo
#

Yeah i was about to ask lmao

#

thanks

hoary mural
#

hey! I'm having an weird issue

when I change the speed in the unity editor, the speed actually changes in the game

but when the speed is changed during runtime by the code, it doesn't seem to be affected, any clue as to why?

this is my ball script:

public class BallScript : MonoBehaviour
{
    public float speed;

    public float tracker;

    public Rigidbody2D myRigidBody;

    public Vector3 startPosition;

    public float increaseFactor = 1.5f;

    


    // Start is called before the first frame update
    void Start()
    {
        startPosition = transform.position;
        Launch();
    }

    // Update is called once per frame
    void Update()
    {

         

    }

    public void Reset ()

    {

        myRigidBody.velocity = Vector2.zero;
        
        transform.position = startPosition;

        tracker = 0;

        speed = 5;

        Launch();

    }

    private void Launch()
    {
        float x = Random.Range(0,2) == 0 ? -1 : 1;
        float y = Random.Range(0,2) == 0 ? -1 : 1;
        myRigidBody.velocity = new Vector2 (speed * y, speed * x);
        
        
    }

and this is the method im using to track and to increase and update the ball speed:

  private void  OnCollisionEnter2D(Collision2D collision)
    {
        if(collision.gameObject.CompareTag("Ball"))
        {

            
            ball.speed *= ball.increaseFactor;
            Debug.Log("speed tracked!");

        

        }
    }

any clue how to fix this? blushie

warm raptor
rich adder
#

ehh

wintry quarry
rich adder
wintry quarry
#

anyway you shouldn't modify public fields on other objects. Poor practice. Make a public method and call that

rich adder
#

GameObject.Find is very slow and doing it inside Update is a curse @warm raptor

#

as to why your bullets are not hitting it could be many things, knowing how you even move the bullet is important

warm raptor
rich adder
#

Updating constantly doesn't mean you should always look for the same component/object if its not missing.

#

Do you hire the same person everyday to make sure they show up to work?

alpine mortar
#

Hello again, I've tried PostProcessing and everything works now except one thing

#

when I change scenes, brightness doesnt work and resets to default when I go back