#šŸ’»ā”ƒcode-beginner

1 messages Ā· Page 220 of 1

slender nymph
#

if the component exists on the prefab you instantiate then Awake and OnEnable are both called before Instantiate returns. if it does not exist on the prefab but you add it via AddComponent then theoretically they will both be called before AddComponent returns as well, but you can always tryitandsee

grim pecan
#

i have the space for it and i dont think any firewalls are blocking it

#

imma restart my computer real quick

frigid sequoia
slender nymph
#

okay so then read past the first sentence

frigid sequoia
#

It should work if I attach the scipt later right? I am thinking if I should just make it part of the general enemy behaviour instead, but not sure

slender nymph
#

surely you bothered to read the entire first message i replied with

frigid sequoia
#

I did, but I was hopping for more precise response than "probably doesn't, but dunno"

#

Alrigth, lets see if it does...

slender nymph
#

the time it took for you to type that message, you could have easily just tested it yourself like i suggested you do

warm condor
#

Hey, is there a way to switch from using the update function to fixed update function? To give you some context, I have this script that is mainly focused on movement and a bunch of calculations to make that movement happend (like acceleration, decelleration, etc.). When I realized that it would be better to use fixed update in the long run and tried to change that, my player makes no moment at all and I don't want to have to change each and every variable because that would waste too much time. So is there an easier way to simplify this prosses?

slender nymph
slender nymph
teal viper
tribal salmon
#

does know what I should do if it says "the system cannot find the file specified" in the assetbuilder?

#

I am very new to unity so idk what to do

warm condor
warm condor
slender nymph
#

Update is called every frame. so it runs at exactly the framerate. provided you are correctly making things framerate independent you will not run into issues

#

you also haven't shown relevant code so we couldn't possibly know what isn't working, but i'd guess that you are probably attempting to get input in FixedUpdate which is typically a no-no

teal viper
calm dust
#

ok, so this is a strech but does anyone want to help me with my game? im not quite sure how to make a map.

warm condor
#

ohh I see, well thank you

slender nymph
eternal falconBOT
calm dust
#

oh ya your right

#

where would i go for that

summer stump
tribal salmon
calm dust
#

i was asking for help

summer stump
cosmic dagger
tribal salmon
#

Moving Temp/unitystream.unity3d to C:/Users/astud/Downloads/LethalSDK_Project/Assets/AssetBundles/testingshit.lem: The system cannot find the file specified.

teal viper
calm dust
#

i wasnt

tribal salmon
slender nymph
cosmic dagger
summer stump
# calm dust i *wasnt*

Then try being clearer. You asked if someone could help with your project instead of asking a question

So we assumed it wasn't a specific question

calm dust
teal viper
summer stump
#

Or try in the !blender server

eternal falconBOT
summer stump
#

Those are the main ways to make maps

cosmic dagger
calm dust
#

ok thanks

tender stag
#

i just had the perfect name for this variable and then forgot it

#

whats a better name for a variable that manages how long it takes friction to change? frictionChangeTime

calm dust
#

yes, its in 3d

slender nymph
calm dust
#

im makins a fps

teal viper
eternal falconBOT
#

:teacher: Unity Learn ↗

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

eternal needle
tender stag
#

duration

#

yeah thanks

cosmic dagger
tender stag
#

the word just suddenly went out of my head

cosmic dagger
#

conversion, transition . . .

grim pecan
#

bro this stuff still aint downloading

#

ive clicked retry so many times, restarted my computer so many times, and check if anythings blocking it, and its still not downloading

buoyant knot
grim pecan
#

probably

buoyant knot
#

that’ll do it

#

maybe send him a christmas gift to patch things up

cosmic dagger
#

did you click the link at all?

chrome veldt
#

try buying another windows key

#

will chill him out

#

anyways, does someone know how to make drag for the player not to slide like a penguin everywhere?

grim pecan
buoyant knot
buoyant knot
#

if controller input is zero, it accelerates to zero

grim pecan
#

itll be fun when playtesting

#

make it a new movement option

chrome veldt
buoyant knot
#

makes no difference

chrome veldt
#

ok, how tho?
||can i copy??||

buoyant knot
#

my player movment script is super complicated. you do not want to copy it

chrome veldt
#

just the part about the speed i said, i'll try to adapt it

#

and also

#

my friends write stuff so bad, it looks like hierogliphs, i can read it

buoyant knot
#

calculate:
target velocity is a function of move input.
delta velocity is a function of target velocity - current velocity, acceleration constant, and delta time

#

i’m not at home anyway rn

chrome veldt
#

ok, i'll try, thanks

buoyant knot
#

and I say you don’t want to copy because i have a bunch of geometry and shit for slopes, and interface for my own custom physics engine

chrome veldt
#

oh, nice

buoyant knot
#

idk i might share later. it is well documented enough that you might get something out of it

arctic stag
#

Hi there! I'm new and I'm wondering how to create blinking led textures? like leds on a terminal panel for example? What technique do you use to achieve this? Thanks!

rich adder
rocky canyon
#

i use a mix of images and lights..

arctic stag
rocky canyon
#

emissive materials

rich adder
rich adder
#

I use perlin noise for my flickering lights for example

arctic stag
#

okay thanks, I'll look into it

rich adder
#

still needs work to sync light component with material.
edit Removed gif dont wanna trigger someones eyes lol

frigid sequoia
#

Ok... so I am trying to add the script that replaces the mats of the meshrenderer temporarilly to the spawned enemy, but it needs to be on the gameobject that actually has the meshrenderer, which is not the top one, also some enemies even have more than one meshrenederer. How can I get those? Something like TryGetComponentsInChildren doesn't exist rigth?

rich adder
#

GetComponentsInChildren

chrome veldt
#

@buoyant knot any ideas in how to jump? the method im using is not working

#

oh, forgot you're not at home, my bad

lament harness
#

why cant i edit sprite shape profile its all just grayed out

frigid sequoia
#

Yes, the awake() does trigger if anyone was curious; just that it does nothing cause the paramaters are not setted up, the component is added with no values whatsoever. Guess I will have to refactor it to account for that

slender nymph
#

yes, that's how it works if you are just using AddComponent because that does not allow you to assign anything to the serialized fields in the inspector beforehand

#

if you want to assign things in the inspector you would need to instantiate a prefab instead of using AddComponent

slender nymph
frigid sequoia
slender nymph
#

that is editor only

buoyant knot
#

this y vel should be a constant

frigid sequoia
#

The thing now is the renderer might be a normal MeshRenderer or a SkinnedMeshRenderer, that's why was seeking for something like TryGetComponentsInChildren instead of just getting them directly. How do I do this?

buoyant knot
#

specifically:
vf^2= vi^2 + 2ad

#

vf = 0, because that is y vel at top of jump arc.
d = desired jump height.
a = gravitational acceleration, which should be rb.gravityScale * Physics.gravity.y

#

and vi is the y velocity for your jump (which needs to get written to rigidbody velocity)

#

which is the initial y vel you need so that you reach exactly that jump height under exactly that gravity

#

understand?

chrome veldt
#

no, but kinda yes

#

no need to explain further, imma make effort to understand

#

i don't want to take much of your time

buoyant knot
#

a lot of people are lazy fucks, and define jump force based on some bullshit number they just move up and down

#

that kinematic eqn gives you exactly the number you need to jump a specific height

low dawn
#

yo can anyone help help remove this outline over my floors n stuff

#

im using an enemy ai and those r the boundaries but idk how to remove them visually

#

wait nvm

tulip hill
#

how do i reference a vector on void update on a completely different method in the same script?

tulip hill
#

lol

#

im still doing it though

buoyant knot
#

you can choose to use math to make your life easier, or struggle with a longer grind. it’s ultimately your choice.

tulip hill
#

ill struggle thank you

chrome veldt
#

the jump method worked, thx random internet person

#

literal 2 lines

tulip hill
#

im trying to jump too

#

im using charactercontroller tho

#

that is apparently the only issue i have everywhere

chrome veldt
#

now for the parkour movementation and tricks

#

(i'll go bald due to stress from doing the animations and coding)

tulip hill
#

help, shows i cant convert vector3 into float, i thought velocity.y was a vector

chrome veldt
#

wait

tulip hill
tulip hill
chrome veldt
#

did it work?

tulip hill
#

the thing is i have charactercontroller instead of rigidbody

#

so no

chrome veldt
#

oh

buoyant knot
tulip hill
#

i'm following brackeys' tutorial on fps movement but he doesnt show jumping

#

thats basically it

#

im trying to just modify the y part of the velocity vector to get it

#

fixed it

#

apparently i was assigning a whole vector to just the y part of the vel. vector

#

i just needed to get rid of the .y in velocity.y

#
void Jump(float jumpParam)
{

    if (isGrounded && Input.GetButtonDown("Jump"))
    {
        velocity = new Vector3(velocity.x, jumpParam, velocity.z);
    }
}```
tulip hill
#

the if statement goes on the void update

chrome veldt
#

nice

tulip hill
#

so the script doesnt work

#

it wont jump

timber tide
tulip hill
#

ok

#
void Jump(float jumpParam)
{
    velocity = new Vector3(velocity.x, jumpParam, velocity.z);
}```
#

so the thing doesnt jump for some reason

#

im going to try putting absurdly high values on jumpParam

chrome veldt
#

nasa wants to know your location

tulip hill
#

still doesnt work

timber tide
#

there's like character controller templates by unity you can start a project with

tulip hill
#

what

timber tide
#

and just rip those apart to see how they do the logic

tulip hill
#

i did not know

#

idk man i wanna do it by myself

#

im technically not even doing it by myself and i know it

chrome veldt
#

no one is

tulip hill
#

yeah

timber tide
#

that's fine, but ideally you should be reading up on a guide because cc isn't beginner friendly

tulip hill
#

yeah i will now

tulip hill
buoyant knot
#

velocity is a Vector3

tulip hill
#

that is what i said

buoyant knot
#

velocity.y is a float

tulip hill
#

i know

#

i corrected it later

chrome veldt
tulip hill
#

yeah

#

brb if you help me ping me

buoyant knot
#

i’m literally telling you not to try to assign velocity.y

#

assign a whole new Vector3 to velocity

buoyant knot
#

in essence, you did nothing

tulip hill
tulip hill
buoyant knot
#

you wrote a vector3 to some variable you call velocity

#

which is not the same as assigning a velocity to your rigidbody.velocity (or character controller)

tulip hill
#

ok

buoyant knot
#

you could rename that variable boogerAIDS, and it wouldn’t change how your code functions at all

tulip hill
#

how do i assign it to charactercontroller?

buoyant knot
#

i don’t have experience with character controller, so you need to look at its actual methods to see how to tell it to move

chrome veldt
#

ok, last question of the day (or not)
how do i make UI?

frigid sequoia
chrome veldt
#

i might be a little cooked, sorry, didn't see that

#

imma go sleep, sorry

frigid sequoia
#

If I do this, the out of the TryGetComponent is setting the parameter above with the same name or just creating a local variable?

rare basin
teal viper
unreal imp
#

Guys, would anyone know how I add ammunition to my gun without it exceeding its maximum capacity? like in half life 2/gmod private void OnCollisionEnter(Collision collision) { if (collision.collider.CompareTag("SmallAmmoBox") && gunHolder.GetComponent<Gun>()) { Gun gun = gunHolder.GetComponent<Gun>(); if (gun.currentAmmo < gun.maxAmmo) { int maxAmmoToAdd = Mathf.RoundToInt(gun.maxAmmo % 25); int ammoToAdd = Mathf.Min(maxAmmoToAdd, gun.currentAmmo); gun.AddAmmo(ammoToAdd); Destroy(collision.collider.gameObject); } } }

    public void AddAmmo(int ammoAmount)
    {
        int ammoReload = (int)(maxAmmo * ammoAmount);
        currentAmmo += ammoReload;
        ammoText.text = currentAmmo.ToString();
        ammoText.text = currentAmmo.ToString();
    }
frigid sequoia
teal viper
frigid sequoia
#

Shouldn't that result on two variables of the same name and prevent me from doing it?

plucky bear
teal viper
frigid sequoia
#

Can I set it to the class parameter then?

teal viper
frigid sequoia
teal viper
#

Only if you declare a new variable.

clear seal
#

!code

eternal falconBOT
clear seal
#
if(Input.GetKey(KeyCode.W))
{
    Animation.Play();
}```
#

is this good for a basic walking animation?

#

like extra simple but not the best

#

does it work?

queen adder
#

You need some extra logic.... but thats something ppl do just play animations via code

#

If u want it to be simple thats fine

teal viper
clear seal
frigid sequoia
queen adder
#

I know godot programmers do it like this

clear seal
#

i mean if it works

queen adder
#

They check all of there animating logic via code instead of the Animator

clear seal
#

i could upgrade it later

#

ĀÆ_(惄)_/ĀÆ

queen adder
#

Its up to u honestly

#

But its harder to maintain it via code

frigid sequoia
queen adder
#

I agree

#

But if its a simple game i think its fine

clear seal
queen adder
#

Is it 2D or 3D

#

How many animations are there?

clear seal
#

so the only thing i should concentrate is the cam

queen adder
#

Its a top down RPG? like the old school zeldas?

clear seal
queen adder
#

Oh....

frigid sequoia
clear seal
#

4 direction animation

clear seal
#

but the character is not that complex

queen adder
#

If its 3D you should definitely use the Animator

queen adder
#

If u do animation.play there isnt any animation smoothing

#

You 100% want that

clear seal
#

well i guess i will use animator then

queen adder
#

So lets say you have a walking animation that transitions to a Run Animation if u start running it will just jump to the running animation making it look very jank lol

#

I thought u were making a simple 2D platformer

clear seal
#

wait

#

so the entry stuff in Animator

queen adder
#

Watch a tut

frigid sequoia
queen adder
#

The animator system is way to complex to go over in a code channel

#

They look jank but without the smoothing it will look EXTREMELY jank

craggy oxide
#

 void OnCollisionEnter(Collision2D collision)
    {

    if (collision.gameObject == player)
    {
    Debug.Log("Collision!");
    }
    }

I've been learning Unity 3D for the past month but I decided to try Unity 2D for once.
The problem according to VS Code is that OnCollisionEnter() is unused
But with Unity 3D, OnCollisionEnter() usually functions as a standalone method that doesn't need to be called
What's the difference? How do I detect 2D collisions if not this way?

frigid sequoia
# clear seal so the entry stuff in Animator

Just a round up for the very basic, create an empty state as the entry, make a variable for each of the axis movements (you can do float or bools), make it so you can transition from any state to any other with no exit time with the condition corresponding to that animation, I am assuming this is what you want to do on a basic 2d rpg

queen adder
#

Hes making a 3D RPG. But those ideas still apply

queen adder
frigid sequoia
queen adder
#

I agree

sage thunder
#

How do i write a mesh to a Skinned Mesh?
I have a small test script that displaces the vertices of a mesh (one of the examples from the mesh API documentation). On a regular mesh with a mesh filter it works fine. But on a mesh with a Skinned Mesh Renderer, it does nothing. What's the proper way to change the vertex positions of a skinned mesh per frame?

teal viper
sage thunder
clear seal
teal viper
#

So any changes you do are not effective, or might cause unpredictable results if actually forced.

frigid sequoia
timber tide
#

oh huh, but this shader isn't part of the material you use on them?

frigid sequoia
sage thunder
# teal viper Yep. For skinned meshes vertices are displaced in the vertex shader to apply the...

Ahhh, hmm. So the deformation caused by the rig is calculated in the vertex shader, or just applied there? I'm trying to adapt some stuff from Blender where all deforms are applied to the mesh independent of any shader. So it is possible to get the deformed position and then modify it before anything renders.

the goal is to compare the base position of the mesh and the deformed position after the rig, and then add some amount to the deformed position.

timber tide
#

that's interesting that it does default to vertex shader cause I can imagine how intensive animation is otherwise

queen adder
#

Thats a state

rich adder
clear seal
#

ok thx

teal viper
# sage thunder Ahhh, hmm. So the deformation caused by the rig is calculated in the vertex shad...

Might be wrong, but afaik, animation is stored as deltas to position/rotation. The animation system creates a transformation matrix for each bone and passes it to the shader. The shader then transforms the vertex position according to that matrix and vertex bone weighs. You could modify the bone to affect all the bound vertices on the CPU side, but if you want precise control over each vertex, you'll probably need to do it in the shader.

frigid sequoia
#

I might be wrong, but the state machine isn't like an special type of state that swaps between several states?

clear seal
teal viper
sage thunder
queen adder
#

OOF

#

That seems perfomance heavy

queen adder
#

You should cache the mesh in awake

teal viper
sage thunder
#

So it sounds like if I want to do mesh operations on a skinned character, it needs to be in the vertex shader. I'll look more into that, thanks!

clear seal
#

how do i call an animator

queen adder
#

Theres no reference to a animator

clear seal
teal viper
clear seal
#

i am gonna add it

queen adder
#

The test reference is never set

#

You mean how do u play an Animation?

teal viper
queen adder
#

Oh my god i didnt even realize that

teal viper
#

What's the correct syntax?

clear seal
teal viper
#

Should probably go through C# basics first before continuing

queen adder
#

Agreed

#

But its animator.Play(string animationName) / animator.Play(int animationID)

craggy oxide
# teal viper How do you call a method in general..?šŸ˜…

if you still wanna know:


// Calling a Method in Unity C#

void MyMethod() // This can be named anything you want as long as the name's unique
{
Debug.Log("Welcome to my method!") // This just displays a new message in the Console
}

void Start() // This could be any Unity method: Start, Update, FixedUpdate, LateUpdate, etc.
{
MyMethod(); // Runs the method whenever the greater method runs (Here, it would activate at game start)
}

// Without annotations

void MyMethod()
{
Debug.Log("Welcome to my method!") 
}

void Start()
{
MyMethod(); 
}
gaunt ice
#

they are not asking for help.....

craggy oxide
#

oh well šŸ¤·ā€ā™‚ļø

worldly jolt
#

Im trying to make a airline sim game and am currently working on perfecting my arcade flight physics. The code is quite messed up and i have spent probably 5 hours on it now just trying to find fixes to all of the bugs i come across. Let me know what you think, im looking for feedback.
Heres the code: https://paste.ofcode.org/7gYHkKsKbua33JfnUWPq5B

Thanks!

teal viper
craggy oxide
supple citrus
#

Anybody know why the function isn't being called?

#

There are no errors so I dont really know where to look

queen adder
#

Why do u have to wait for the end of the frame?

#

Im guessing its the yield return

summer stump
# supple citrus

Coroutines should be started with StartCoroutine
Which you can't do from another class afaik

supple citrus
#

It worked 1 time like this and I don't remember changing anything

summer stump
#

So you should make an intermediary method that callse StartCoroutine

queen adder
#

I still dont understand why this is a coroutine at all

supple citrus
#

i cropped

queen adder
#

if ur trying to wait until the File is done being read that shouldnt be a coroutine

supple citrus
#

ReadPixels() can only be called at the end of a frame after everything has rendered

#

It worked once lol, it screenshot the screen and saved a png file.

#

Now the function isnt being called at all

#

I think the actual contents of the function is fine because I haven't changed it

#

And because I directly copied it since I had no idea how texture stuff worked

#

The Yield Return is whats messing it up

gaunt ice
#

what ienumerator actually is

supple citrus
#

But I cant call ReadPixels() unless its at the end of the frame

#

As far as I know

queen adder
#

You have to call StartCoroutine()

supple citrus
#

is there an article for that because Ive never heard of it

#

And the Unity website always gives a huge scary block of code as the example

gaunt ice
#

ienumerator is state machine

#

and each yield return creates a new state
btw i am not the one who write c# compiler so i maybe wrong, better ask in c# discord

native seal
#

!code

eternal falconBOT
supple citrus
#

Could I call it from LateUpdate() without having to yield return?

queen adder
#

I was thinking LateUpdate() could work but idk if thats EndOfFrame

gaunt ice
#

just start coroutine......

queen adder
#

StartCorutine() Will for sure work tho

supple citrus
#

What does this mean lol

#

Ive never used it

queen adder
#

Jk

#

Its the only way to start ur method.

supple citrus
#

So what

#

StartCoroutine(thumbnailmanager.GetThumbnail())?

#

because I dont understand

queen adder
#

Yes

supple citrus
#

oih

#

Thank you it works

#

But i dont understand why xd

#

What did StartCoroutine() Do that calling it normally didn't

queen adder
#

Could prolly better explain than any of us

pliant sparrow
#

This is giving me trouble, im storing the music and sfx audio levels in playerPrefs, when I reload the scene sfx gets reset to 1

#
    private void Load()
    {       
            musicSlider.value = PlayerPrefs.GetFloat("music");
            sfxSlider.value = PlayerPrefs.GetFloat("sfx"); 
    }
#

but when I swap those 2 lines of code the opposite happens

#

music gets reset to 1

slender nymph
#

you're probably doing things in their onValueChanged event. use SetValueWithoutNotify instead

pliant sparrow
#

this is using sliders, is that a slider setting or am I missing something

slender nymph
#

it's a method

zinc shuttle
#

why cant i make player object collide with enemy object and it destroy player object
i tried everystep i dont know where did i made mistake

!code

slender nymph
#

see #854851968446365696 for what to include when asking for help because that is certainly not enough context to know what your issue is

pliant sparrow
#

could I send the script so you can maybe explain how to use it

slender nymph
#

you call that method instead of assigning to the value property

pliant sparrow
#
    public void ChangeMusic()
    {
            Debug.Log("ChangeMusic");
            mixer.SetFloat("MusicVolume", Mathf.Log10(musicSlider.value) * 20);
            Save();
    }
slender nymph
#

that method is 100% irrelevant to what i suggested

slender nymph
pliant sparrow
#

oh ok I thought it was used in the other function

slender nymph
#

why

#

the method's name literally starts with "SetValue". I suggested you use that after having only seen you assign to the value property.

pliant sparrow
#

ok yes thank you, that worked

hybrid wagon
#

issues with debug mode bump

low robin
#

i have a problem with XR. in the first scene my XR origins hands move properley, but when i switch the scene the hands don't move

queen adder
grizzled zealot
#

How can it be that this outputs 1? Am I am misunderstanding Mathf.Lerp?

queen adder
#

!code

eternal falconBOT
queen adder
#

Show the whole thing please šŸ™‚

hybrid wagon
queen adder
#

Inside of the for loop

#

do

#

(for int i = 0; i < vertices.length - 1; i++)

grizzled zealot
supple citrus
#

Maybe because your t is 7?

#

Or does this mean the 7 will be clamped down to a 1 anyway

hybrid wagon
grizzled zealot
hybrid wagon
#

also, altering the for loop to be that minus one doesnt seem to fix it

ivory bobcat
zinc shuttle
hybrid wagon
#

specifically when pixel density is 2, anyway for that reason

#

i goes to 12 and j to 2 when pixel density is 3

queen adder
#

Where is the UV array defined?

hybrid wagon
#

theyre used like this

ivory bobcat
#

The fit being thrown was about index out of range so one of your arrays isn't the size of i

#

What was the Unity Editor error?

hybrid wagon
#
StyleBoxProcedural.GenCorner (UnityEngine.Vector2 pos, UnityEngine.Vector2 stretch_factor, System.Single corner_radius, System.Boolean outline, System.Single border_start, System.Single border_end) (at Assets/CatUI/Theming/StyleBoxProcedural.cs:72)
StyleBoxProcedural.UpdateMesh (UnityEngine.Rect rect) (at Assets/CatUI/Theming/StyleBoxProcedural.cs:118)
StyleBox.Render (CatUI.Drawing.Drawer drawer, UnityEngine.Rect rect) (at Assets/CatUI/Theming/StyleBox.cs:21)
UIElement.DrawStyleBox (StyleBox box, System.Nullable`1[T] rect) (at Assets/CatUI/UIElement.cs:68)
UIElement.DrawStyleBox (System.String id, System.Nullable`1[T] rect) (at Assets/CatUI/UIElement.cs:73)
CButton.Update () (at Assets/CatUI/CButton.cs:21)
queen adder
#

His code actually looks right to me tho

#

Show me the entire class

ivory bobcat
#

The error may be elsewhere - I'm not aware of the initial problem.

queen adder
#

I dont think its that

hybrid wagon
#

one sec making a code paster

ivory bobcat
#

Assuming we were shown random code not related to the problem

queen adder
#

I think its somewhere else

hybrid wagon
#

i want to say that this is code given to me by someone else to work on

queen adder
#

The method you showed isnt the method unity is complaining about

hybrid wagon
#

oen sec

hybrid wagon
#

and im trying to figure out how to increase pixel density

#

so far not working

hybrid wagon
hybrid wagon
queen adder
#

Its just this one class

hybrid wagon
ivory bobcat
#

Where is CButton?

low dawn
#

does anyone have a good color theme for an alien planet

hybrid wagon
#

ah one sec

ivory bobcat
hybrid wagon
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[AddComponentMenu("CatUI/Button")]
[DisallowMultipleComponent]
[ExecuteAlways]
public class CButton : SelectableElement
{
    public override string Category => "button";
    // Update is called once per frame
    protected override void Update()
    {
        base.Update();
        if (mouseDown) {
            DrawStyleBox("pressed");
        } else if (hovered) {
            DrawStyleBox("hover");
        } else
        {
            DrawStyleBox("normal");
        }
        if (focused)
        {
            DrawStyleBox("focused");
        }
        FinalizeDraw();
    }
}
queen adder
#

Im guessing it has something to do with this i honestly cant even read 90% of the code tho

#

vertices[((i * 4) + j)] = new Vector3(vertex.x, vertex.y, 0);

#

On line 72

hybrid wagon
#

first i gotta even understand where it begins

queen adder
#

Well the error message says the index goes out of range when u call the method on line 118 inside of the StyleBoxProcedural Class

#

The only time u access an array is on line 72

ivory bobcat
queen adder
#

I was looking at that to but i cant even comment on it because i have no idea what he was trying to accomplish

ivory bobcat
#

There doesn't seem to be any early escape patterns so if i is anything more than vertex count when multiplied by 4, the line will throw an index out of range.

hybrid wagon
#

i got it to render, a little anyway

#

corners dont at all but

#

it doesnt immediately explode

queen adder
#

Whats the point of all the code?

ivory bobcat
#

The dirty solution would be to set the delimiter to i * 4 + pixelDensity < vertex_count - without not knowing what the code is supposed to do..

hybrid wagon
#

this was my dirty solution for the time being lol

queen adder
#

Tisk tisk

hybrid wagon
#

its a bit broken

queen adder
#

Again why all the code tho?

hybrid wagon
#

the border color is now inside

hybrid wagon
#

the gencorner does as the name implies, generates the pixels for a corner

#

is used 8 times, 4 for the outside border and 4 for the inside corner

lavish gate
#

Didnt look like it

#

I typed Destroy and it was green and not yellow

#

It extends from monobehaviour im guessing

polar acorn
potent nymph
#

how would I adjust this background image to dynamically fit the height of the text?

#

As far as I know, the text can overflow but its height remains unchanged

potent nymph
#

this is a scripting problem, is it not

eternal needle
#

if you wanted to do it through code, tmp has stuff like its desired height from the text

#

but should be possible through just existing ui

potent nymph
#

I don't think it's possible through the UI, when I searched online there was a variety of scripting solutions in combination with components that didn't quite work for me https://stackoverflow.com/questions/46019256/unity-ui-textbox-dynamic-height-how-do-i-make-it-expand-based-on-text-amount

tepid summit
low dawn
#

the last purple is def the best

#

tyty

tepid summit
#

ikr

#

allg

#

im good @ hex codes

eternal needle
#

the first answer uses the content size fitter, which really should be fine for this. though the ui channel is still probably more relevant.
tmpro has some values you could use, but the content size fitter would be doing the same thing

rough dust
#
            // Clone the prefab
            if (currentIslands.Contains(i + 1))
            {
                islandImage = Instantiate(greenIslandPrefab, islandPosition, Quaternion.identity);
            }
            else
            {
                islandImage = Instantiate(islandPrefab, islandPosition, Quaternion.identity);
            }

            // Edit the on click function of the button
            Button button = islandImage.GetComponent<Button>();
            button.onClick.RemoveAllListeners();
            button.onClick.AddListener(() => IslandClickedEvent(i));

I'm not sure why this isn't working.
I have a function that generates islands in my game, and the "Clone prefab" part does what it says, it uses my greenIslandPrefab and islandPrefab to make a copy, then my problem arrives.
The on click changing doesn't seem to work and I don't know why.
I added a debug statemet checking if button isn't null, and no debug log shows, so button isn't null, so I don't understand why it wont work. The listener's aren't cleared, and no new listener is added

#

(islandImage is defined outside of the if statement, so islandImage in Button button = islandImage.GetComponent<Button>(); isn't the problem

Also yes, the cloned game objects DO have a button property

abstract marlin
#

Hi Guys i have some finalization Problems with my Flappy Bird Project from Zigorous.
Im All the Way to the UI Part and i want to implement my ScoreText into my GameManager.

  • using UnityEngine.UI; <- is in the GameManager , also Created as an UI - Text (Text Mesh Pro) (Old Guide from 3 Years ago uses just Text.

Small Changes i did apart from the Original Video was that i couldnt just drag my Font as usual into the Space , i had to Create a Font over Window - TextMeshPro - Font Creator. Dragged the github into it and only did a 1024 x 1024 size and created it.

Beside that i followed all Steps from Guide but the Game Manager wont allow me to pull it in as a Text , it Marks it as a GameObject and only allows me to put it as one.

I tried a bit around but dont Understand why my Text isnt applied as it.

Picture Shows my GameManager , My Score Text Settings , maybe someone knows why Unity shows it as a GameObject...

eternal needle
# rough dust ```cpp // Clone the prefab if (currentIslands.Contains(i...

whats indicating to you that the listeners arent cleared? if you debug anywhere between those statements, and you dont have any errors, then all non persistent listeners should be removed.
Maybe it is affecting the wrong button, or maybe your game isnt registering a button press at all. Could be the case if you dont have an event system in your scene

static bay
#

It's Unity's legacy text element.

teal viper
abstract marlin
static bay
#

The TextMeshPro one exists in the namespace using TMPro and the type is TMP_Text.

teal viper
static bay
#

you should be able to slot it in then

rough dust
# eternal needle whats indicating to you that the listeners arent cleared? if you debug anywhere ...

The video shows that both my load and create island functions are called in start (depending on if a save file is found), then I show when the game runs, in the console log it says islands have been loaded because a save file was found. And you can see islands being created, as clones as their prefabs, but the button property isn't changed at all.
Even with button.onClick.RemoveAllListeners(); the buttons all still have the same on click property. And I just can't figure out why, because the buttons are being created correctly, their names are changed using the islandImage game object, their positions are changed, etc after I attempt to edit their button properties.

eternal needle
rough dust
#

Yes

#

thank you XD

teal viper
abstract marlin
static bay
#

Dont bother with that old Text.

#

It's Legacy for a reason.

#

Programmers didn't slave away in the SDF mines for years only for people to not use them 😠

eternal needle
# rough dust

those are persistent listeners, not affected by RemoveAllListeners

pallid nymph
#

on an unrelated note, am I the only one who highly dislikes the somewhat common approach of calling RemoveAllListeners before adding a listener?

rough dust
teal viper
#

If you don't want multiple subscribers, why not use a simple delegate then?@pallid nymph

teal viper
#

I've never thought that was a common approach. Never encountered it in someone's code.

eternal needle
pallid nymph
rough dust
eternal needle
eternal needle
pallid nymph
rough dust
#

Oh.. wow that's weird.
Well my issue is fixed then XD
Thank you!

low dawn
#

i js spent like 3 hours on a Is Triggered bug

#

i hate my life

static bay
#

Welcome to game dev. Sanity not included.

eternal needle
rough dust
eternal needle
rough dust
#
            // Edit the on click function of the button
            Button button = islandImage.GetComponent<Button>();
            button.onClick.RemoveAllListeners();
            button.onClick.AddListener(() => IslandClickedEvent(i));
#

I checked the first button, which at that point, i equals 0. But it returns 42 XD

eternal needle
#

store i in its own variable and then use that variable, let me find a link which explains it

ivory bobcat
#

The lambda will only catch the final value of i

eternal needle
rough dust
#

Yes, it was a loop, part of a loop actually
And redeclaring the variable worked! Thank you!
Now time to run into 50 other issues, or well, knowing the scope of my game, 4569206 šŸ™‚
I definitely dont regret getting into coding lol

#

I just realized, It's 3AM 0_0
Good night... I don't have a problem

abstract marlin
queen adder
#

i just made a game with the help of GMTK's video and ive learnt a lot and i want to make a 2d platformer right now would it be a good idea to start now or should i make some more small games?

queen adder
#

its a flappy bird rip off

unique hornet
#

Hey guys, im trying to create a 2d side scrolling shooter. Looking for some help with collision. I have a script for my spaceship to fire a bulletprefab. However I cant seem to get the bullet to destroy any object. When I play the game I can visually see collision but nothing is registered in my console log (except for the fact that my bullet is colliding with itself somehow).

    {
        Debug.Log("Collision detected with object tagged as: " + collision.gameObject.tag);
        // Check if the collided object is not tagged as "Player" and it's not a bullet
        if (!collision.gameObject.CompareTag("Player") && !collision.gameObject.CompareTag("Bullet"))
        {
            // Destroy the collided object
            Debug.Log("Bullet collided with: " + collision.gameObject.name);
            Destroy(collision.gameObject);
        }
    }
}```
static bay
#

If it's a simple 2D platformer ala Super Mario Bros, go for it.

#

If it's a full on metroidvania like Hollow Knight... probably want to get more practice in >_>

queen adder
pallid nymph
#

I'm not sure I agree with the implication that Super Mario is simple... but okay šŸ˜„

#

Generally, I think the trickiest part about a platformer is the character controller... one can make a simple one, buuut the more features you want ot add, the more and more tricky it'll become

static bay
#

Obviously you can go nutty with the character controller.

#

But I assume this guy isnt.

queen adder
#

i mean i do

#

want a satisfying controller with dashes gliding wall jumps

pallid nymph
#

yeah, so that's going to be very difficult

static bay
#

yes that's quite a bit more complicated

#

I mean, I think it'll be a good learning experience.

#

State management, physics, etc.

#

But it's definitely a few steps up from flappy bird.

queen adder
#

should i learn through tutorials while making the gaame?

#

like ill maake the game through tutorials but learn as well

zinc plover
#

I need help to fix this error im having after updating my project

hallow iris
#

!code'

eternal falconBOT
hallow iris
#

any pointer in the right direction would be appriciated

tawdry rock
queen adder
hallow iris
#

i have a ground check layer setup for movement

tawdry rock
#

simple way is then make a variable int timesJumped = 2; each time you jump timesJumped--; and each time you try to jump check if(timesJumped >= 1) when you collide with the ground reset timesJumped = 2;

static bay
hallow iris
tawdry rock
#

if your second if is the collide check then dont need to make a nested if

ivory bobcat
#

You'd probably want the jump counter to be a class variable if you aren't wanting it to reset every frame

tawdry rock
#

otherwise if you jump only once you wontr be able to jump 2 times next since you only reseting if the counter is 0

candid gorge
#

Hey guys, for the past few days I've been trying to make a dash for my game but I can't manage to make it consistent.
Firstly it seems that its framerate dependent because I'm not always getting the same distances, and I don't know how to approach this.
Secondly, for some reason I can't manage to make the dash go where the player is exactly looking with the camera, like if there is some delay
Maybe some of you guys can help me a bit, I'll appreciate it a lot. This is all the code that involves dashing

public void OnDash(InputAction.CallbackContext context)
{
    if (context.started) dashTriggered = context.ReadValueAsButton();

    if (context.canceled) dashTriggered = context.ReadValueAsButton();

    if (context.started && !grounded) dashPerformed++;
}

private void Update()
{
    Dash();
}

private void Dash()
{
    if (grounded)
    {
        dashPerformed = 0;
        dashing = false;
    }

    if (dashTriggered && !grounded)
    {
        if (dashPerformed <= maxDashes)
        {
            performDash = true;
        }
    }

    if (performDash)
    {
        dashing = true;

        Vector3 moveDir = transform.InverseTransformDirection(cam.transform.forward) * dashDistance;
        Vector3 targetDashAmount = moveDir;

        dashAmount = Vector3.SmoothDamp(dashAmount, targetDashAmount, ref smoothMoveVelocity, 0.15f);
        Vector3.ClampMagnitude(dashAmount, maxForce);

        StartCoroutine(PerformDash());

        Invoke(nameof(ResetDash), dashDuration);
    }
}
IEnumerator PerformDash()
{
    float startTime = Time.time;

    grav.gravForce = 0f;

    while (Time.time < startTime + dashTime)
    {

        transform.Translate(dashAmount * Time.deltaTime);

        //Invoke(nameof(DelayedDash), 0.025f);

        yield return null;
    }
}

private void ResetDash()
{
    dashing = false;
    grav.gravForce = gravForce;

    performDash = false;
    dashTriggered = false;
}```
hallow iris
#

it is still giving me the same problem with the jump counter

abstract marlin
eternal needle
hallow iris
grand sigil
#

Are data that are changed during runtime saved when it is on a scriptable object?

#

Like, when i stop then play again, will the value be retained?

eternal needle
#

In the editor they may save because you are directly modifying the asset. In a build it will not work

grand sigil
#

Aight

#

Is there a term/feature is should use when storing a large amount of data?

tawdry rock
# hallow iris it is still giving me the same problem with the jump counter

Didnt tested but should work. Make a trigger collider for the ground tho or use oncollisonenter2d instead.

  [SerializeField] private int jumpCount = 0;
  [SerializeField] private bool canJump = true;

  private void Update()
  {
      if (Input.GetKeyDown(KeyCode.Space) && canJump && jumpCount < 2)
      {
           DoTheJump();            
      }

      if (jumpCount >= 2)
      {
          canJump = false;
      }
  }

  void DoTheJump()
  {
      jumpCount++;

      // do the jump code here, apply your velocity
  }

  private void OnTriggerEnter2D(Collider2D col)
  {
      if (col.CompareTag("Ground"))
      {
          jumpCount = 0;
          canJump = true;
      }
  }
eternal needle
eternal needle
grand sigil
#

Aight thanks

candid gorge
eternal needle
#

If it is starting many coroutines, then itd be making one per frame which explains the distance issue you mentioned

candid gorge
eternal needle
candid gorge
#
private void Dash()
{
    Vector3 dashDir = transform.InverseTransformDirection(cam.transform.forward);
    Vector3 targetDashAmount = dashDir;

    dashAmount = Vector3.SmoothDamp(dashAmount, targetDashAmount, ref smoothDashVelocity, 0.15f);
    Vector3.ClampMagnitude(dashAmount, maxForce);

    Debug.Log(dashAmount.magnitude);

    if (grounded)
    {
        dashPerformed = 0;
        dashing = false;
    }

    if (dashTriggered && !grounded)
    {
        if (dashPerformed <= maxDashes)
        {
            performDash = true;
        }
    }

    if (performDash)
    {
        dashing = true;

        /*Vector3 moveDir = new Vector3();
        moveDir = transform.InverseTransformDirection(cam.transform.forward) * move.y + transform.InverseTransformDirection(cam.transform.right) * move.x;

        if (move.magnitude == 0f)
            moveDir = transform.InverseTransformDirection(cam.transform.forward);

        moveDir = moveDir.normalized * dashDistance;*/

        StartCoroutine(PerformDash());

        Invoke(nameof(ResetDash), dashDuration);
    }
}```

I took outside the loop the vector calculation so it is performed every frame, and now the debug shows me that dashAmount is some what around 0.8 and 1
#

every time I move the cursor it changes and then the value increases until it reaches 1

short sigil
#

I am trying to make a animation play when walking the character. It worked for pressing W, but when i added that it should play it too, when S is pressed it only worked for S. I found a solution but why didnt it work.

        if (Input.GetKey(KeyCode.W))
        {
            transform.Translate(Vector3.forward * speed * Time.deltaTime);
            direction = transform.rotation = Quaternion.Euler(0, 0, 0);
            anim.SetBool("isWalking2", true);
        }
        else
        {
            anim.SetBool("isWalking2", false);
        }   
        if (Input.GetKey(KeyCode.S))
        {
            transform.Translate(Vector3.forward * speed * Time.deltaTime);
            direction = transform.rotation = Quaternion.Euler(0, 180, 0);
            anim.SetBool("isWalking2", true);
        }
        else
        {  
            anim.SetBool("isWalking2", false);
        }```
#

it worked with this

        if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.D))
        {
            anim.SetBool("isWalking2", true);
        } else
        {
            anim.SetBool("isWalking2", false);
        }```
pale nimbus
#

theres a button and i want to change it to everytime clickable one

tawdry rock
#

i want to make some blood decals but first i need to know if i can place my decals or not so i shoot a ray (blue color) from impact point to where the bullet (yellow ray) originally goes. why is it not detecting the wall? (it's tagged correctly and the enemy collider should be ignored)

  public void ShootRayOnImpact(Vector3 impactPoint, Vector3 direction)
  {
      Debug.DrawRay(impactPoint, direction * 10, Color.blue, 3f);

      RaycastHit blueRayHit;

      if (Physics.Raycast(impactPoint, direction * 10.0f, out blueRayHit, ~ignorme))
      {
          if (blueRayHit.collider.gameObject.CompareTag("FS/CON"))
          {
              Debug.Log("blood splash reached the wall so you can spawn decals");
          }
      }
  }

this is where from it gets the input: hit.transform.GetComponentInParent<bloodSplat>().ShootRayOnImpact(hit.point, fwd);

if i debug Debug.Log(blueRayHit.collider.gameObject.name); nothing appears on the console.
edit: even if i don't use layermask still nothing on console.

hallow iris
queen adder
#

!ide

eternal falconBOT
split dragon
#

Hi. I have a problem: I have an action in void Start, and it only works 1 time in the entire time (as it should be), but I need that if the object is active, then void Start works again on 1 frame. I have an object running, void Start works, but if I turn off the object and turn it on again, void Start will no longer work. How do I make void Start work every time I turn on an object 1 time per frame?

timber tide
#

why not just use update

gaunt ice
#

use onenable
and it is called as method no void, void is return type
and if you hope it runs every frame, use update

split dragon
timber tide
#

update runs each frame

gaunt ice
#

then use update

split dragon
# timber tide update runs each frame

If I put Start() in void Update, then the action in void Start will be done every frame when the object is active. I need the action to be done only 1 time if the object is turned on. Optimization

scarlet tiger
#

use OnEnable if you want something to happen each time the gameobject is set active

timber tide
#

"How do I make void Start work every time I turn on an object 1 time per frame?"

#

Im getting mixed messages here

scarlet tiger
#

yeah, the wording is off

timber comet
#

!code

eternal falconBOT
timber comet
timber comet
rocky canyon
#

ur jump adds force but ur Move Function manually overriding the y velocity..

#

so when u jump it might increase just a very very small fraction.. and then the move function uses that fraction and sets it to be that each frame..

#

it wont continually go up

timber comet
#

so how can i do it? 'Cause if i set that to 0, its also a problem

rocky canyon
#

u should instead

  • when ur jumping using a bool so it does a different thing
  • also when you start the jump zero out any forces on the y
#

you need gravity

#

wait its a rigidbody.. why do u need to set its y velocity?

timber comet
#

or at least, idk how to do that in another way

timber comet
rocky canyon
#

yea a bool should straighten it up

#
    // Zero out y velocity to prevent unwanted vertical movement
    if (!_isJumping)
    {
        _rb.velocity = new Vector3(_rb.velocity.x, 0, _rb.velocity.z);
    }```
#
void Jump()
{
    // Make Player Jump
    if (!_isJumping)
    {
        _rb.AddForce(Vector3.up * jumpSpeed, ForceMode.Impulse);
        _isJumping = true;
    }
}```
#

something similar to this..

#

im sure u can figure it out

timber comet
#

k thanks

grand sigil
#

what is the value of the first dropdown option? is it 1 or 0?

turbid bridge
#

If possible can anyone help me understand what ive done wrong please Assets\Scripts\SettingsMenu.cs(380,33): error CS0103: The name 'coinBeds2sDropdown' does not exist in the current context https://i.imgur.com/EtWDXlh.png

gaunt ice
#

show where you declare coinBeds2sDropdown
and !ide

eternal falconBOT
turbid bridge
#

ok i did that one but now have Assets\Scripts\SettingsMenu.cs(383,17): error CS0111: Type 'SettingsMenu' already defines a member called 'ChangecoinBeds2' with the same parameter types https://i.imgur.com/Tdgg0BG.png

cosmic dagger
turbid bridge
#

and that name cBeds2 is not used for anything else but what i wanna use it for

#

i can share file if it help understand

cosmic dagger
#

Also, did you clear the previous error from the console?

turbid bridge
languid spire
eternal falconBOT
turbid bridge
#

yes i cleared the error

keen dew
#

You have 3 definitions for ChangecBeds2 in the class

turbid bridge
#

i coped what was already there for another item and renamed what i need

keen dew
#

What part do you not understand?

rich egret
#

Someone know how to save the Inventory?

cosmic dagger
rich egret
#

I cant to use PlayerPrefs

cosmic dagger
rich egret
#

Do you happen to have a tutorial video?

turbid bridge
#

so i copied one thing for example public TextMeshProUGUI showCoinDoorImagesLoc; and changed the CoinDoor to cBeds2 public TextMeshProUGUI showcBeds2ImagesLoc; and everything that had CoinDoor on i had also copied it and replaced the same CoinDoor with cBeds2 so everything should be right

keen dew
#

Those have nothing to do with the error

whole idol
#

I wanna import the old standard assets into my unity

#

these assets

queen adder
#

!code

eternal falconBOT
whole idol
queen adder
#

Share the code diamond

cosmic dagger
whole idol
queen adder
#

No offense

#

I'm not downloading that file lol

#

You can use one ot those websites

whole idol
#

im just asking how do i import the file on my unity

#

lol

cosmic dagger
eternal falconBOT
languid spire
queen adder
#

I was talking to diamond not u yodaarc

whole idol
#

oh, gotcha

timber comet
queen adder
#

Sorry for the confusion

turbid bridge
broken lance
#

sorry, do I ask for help here?

timber comet
languid spire
queen adder
#

You can't define a method with the same name and parameters twice

timber comet
queen adder
#

I forgot to put name sorry I mistyped

#

Your application wouldn't know which method to call at runtime.

turbid bridge
#

Thank you for the help that made more sense i appreciate the help

whole idol
#

Ok so this is the custom package. Can I just drag drop it somehow in a way that my cursor doesn't cancel out?
( Please Ignore the unfathomably sexy pictures of Leon kennedy )

#

why doesnt it let me drag drop the assets here for example ?

languid spire
whole idol
#

it's just a folder of folders of folders ... of more folders

languid spire
#

why not drag/drop in FileExplorer?

whole idol
#

Wdym? It's already in fileExplorer, I just wanna import all this folder-inception into unity gang

lost anvil
#

is it possible to physically push open doors without a rigidbody attached to the door itself?

languid spire
whole idol
#

oh i see what you mean

languid spire
lost anvil
#

would i do it with raycasts?

languid spire
#

no

lost anvil
#

how would i go about doing it then?

languid spire
#

attach a collider to both the door and whatever is doing the pushing

lost anvil
#

yeah ive got all that

#

oh, ive got a seperate script for controlling rotation for my door so i dont actually have a hinge component on it

#

if thats what your thinking ive got

languid spire
#

I am presuming you know how to open a door, yes

lost anvil
#

yeah

median sapphire
#

question, say for example i have this skill slots that can be activated whenever I click on it. What's the best method when I want to auto activate it without clicking whenever the skill is not on cooldown?

whole idol
#

Ok so I pasted the entire folder into packages of my current Unity project.... I named it Babuska. It's in the file_explorer and everything but it's not visible on unity blushie

languid spire
lost anvil
whole idol
#

cause i thought it would be easier to navigate the chaotic folderpocalypse using the fileExplorer like u recommended a few minutes ago

lost anvil
whole idol
#

@lost anvil ĪˆĪ»Ī»Ī·Ī½Ī±Ļ‚;

#

nice

languid spire
whole idol
#

oh true

languid spire
lost anvil
#

by clicking and holding and moving the mouse

#

just dragging it

languid spire
#

I meant how do you tell the door to open

lost anvil
#

raycast

#

you want me to send script?

languid spire
#

no, the answer I wanted was with a script. Which method do you use?

lost anvil
#

wdym

languid spire
#

the code must be in a Method somewhere

#

what is it;s name

lost anvil
#

just DragDoor if so

languid spire
languid spire
lost anvil
#

ill just send the script because im not sure what you mean

languid spire
#

Yellow triangle warniing. Red circle Error

languid spire
lost anvil
#

idk

whole idol
lost anvil
#

oh do you mean like void blah() {}

languid spire
#

well that is a method, yes and the name would be blah

whole idol
#

Ill just ignore it šŸ˜„

lost anvil
#

float GetRotation()

languid spire
#

so you have no code that handles collisions?

lost anvil
#

and i set the target position in Update()

#

no not apart from hit.collider etc from the raycast

languid spire
#

that does not 'handle' collisions

lost anvil
#

ive only been doing unity for a week i dont know this stuff unfortunately

#

so no i guess not

languid spire
#

and maybe do !learn before you go much further

eternal falconBOT
#

:teacher: Unity Learn ↗

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

abstract finch
#
    {
        var values = Enum.GetValues(typeof(T));
        int random = UnityEngine.Random.Range(0, values.Length);
        return (T)values.GetValue(random);
    }```
How do I actually use this function to get a random enum? It doesn't let me pass in the enum
cosmic quail
abstract finch
#

trying it now thanks

#

thanks it works ``` LootType randomLootType = SpawnAlgorithms.RandomEnumValue<LootType>();

languid spire
whole idol
languid spire
#

Also google before asking, there are a million explanations for this on the web

simple sun
amber nimbus
#

Hello, I have a question about public variables. If I have a script called Movement and I have multiple Movement scripts in a scene. Inside the script I have a public variable for example speed. Now if I change speed from 10 to 5 would this be changed on all Movement scripts or only the one Movement script I specify?

summer stump
languid spire
#

if you change it in the script it wont change ANY existing instances

amber nimbus
#

so if I make it a static variable it will change in all the scripts?

cosmic quail
amber nimbus
languid spire
#

then static is what you want

swift crag
#

Static fields can't be serialized, so they won't appear in the inspector, mind you

cosmic quail
amber nimbus
#

Aight that is great thanks guys :D

chrome wadi
frigid sequoia
rocky canyon
#

but ya, most solutions are to use a physics material thats using low friction. and apply it

chrome wadi
#

Thanks

abstract finch
#

I got this off a google search but im getting an error in the enum.GetValues portion. Do I have to pass in the enum?

rich adder
abstract finch
#

yes it says Enum doesnt exist in the current context

timber comet
timber comet
abstract finch
#

but I dont know how I would be able to pass in an enum without defining it

rich adder
#

thats right, you're probbaly missing the namespace

abstract finch
#

I want to be able to have it use any enum

rich adder
#

do you know what that is ?

timber comet
rich adder
abstract finch
clear seal
#

i wonder how super mario 64 camera works

timber comet
swift crag
#

Because System also provides a Random class.

#

You can use another using directive to fix the ambiguity, though

abstract finch
swift crag
#
using UnityEngine;
using System;
using Random = UnityEngine.Random;
rich adder
#

type System.Enum

#

see if work

abstract finch
#

it works

#

what does that mean exactly?

rich adder
timber comet
#

Did Unity not override default Random?

swift crag
abstract finch
#

ah i see now

swift crag
#

UnityEngine.Random is a class and System.Random is a class

rich adder
swift crag
#

If you have using directives for both UnityEngine and System, Random is now ambiguous

abstract finch
#

I changed the class to where that function was and the erorr came up the new class doesnt use System

timber comet
#

So why using both Random? One is better then the other?

swift crag
#

they aren't trying to use both Random classes

rich adder
#

they're not

swift crag
#

they just happen to want something from System and something from UnityEngine

#

and this winds up making Random ambiguous

rich adder
#

the compiler wants to know which Random you want since they exist in both Namespaces

timber comet
autumn tusk
#

is there an equivalent of findobjectwithtag for spriterenderers

#

basically i want to change sprite sprite using the spriterenderer attached to the gameobject with the "heldweapon" tag

rich adder
#

not tag

summer stump
rich adder
#

better if you can to just have a serialized field ^^

swift crag
#

I suppose you could find an object with a tag and then get a component from it

#

but that's getting really damn brittle

rich adder
#

esp on the same object lul

rocky canyon
#

u could write u some static methods that do that for u.. but it would end up searching for gameobjects itself

swift crag
#

assign a reference to the sprite renderer in the inspector and you're done

autumn tusk
swift crag
#

it depends on a lot of little things

#

like there being exactly one object tagged "heldweapon"

#

and that the sprite renderer component is attached to that object, and isn't on a child of the object

swift crag
autumn tusk
#

its fine since i will only ever have one player

autumn tusk
swift crag
#

so what?

autumn tusk
#

lemme see this

swift crag
#

i've made plenty of games with prefabbed weapons

summer stump
swift crag
#

I've never searched for an object by name or tag, ever -- other than MainCamera, I guess (:

autumn tusk
#

ok lemme explain right

#

im working on a roguelite type system

#

gonna have weapon pickups that are placed in by the level itself

summer stump
rich adder
swift crag
#

you especially don't want to be using Find if you've got weapons littered all over the level (:

final kestrel
#

If i subscribe to an event on OnEnable, It will listen to it whenever it happens no matter how long right? or until I unsub?

swift crag
#

you want to have a nice Weapon component that gives you everything you need

swift crag
#

nothing is particularly "special" here

rich adder
swift crag
#

in fact, it's good to realize that there's not much "special" going on in your code! I used to think calling Update or Start yourself was "bad" in some abstract way

final kestrel
#

All right thanks a lot.

swift crag
#

but no! you can just do it whenever you want!

small mantle
#

I'm making a Goblin Enemy. When it gets close enough to the Player it will start throwing Spears. The issues right now is that the bullet won't shoot left as the code doesn't tell it to do that. I just want to know how I can simply implement that. For context I havee three scripts, Spear Gob, Spear Gob Combat, and Spear. The Spear Gob script makes the move to Player and rotate if its going left. The Spear Gob Combat makes the Gob attack when close and spawn the Spear. The Spear Script simply adds a velocity at its spawn. 2D Game*

autumn tusk
swift crag
autumn tusk
#

main thing is how to do i get it to identify the spriterenderer of the player

swift crag
#

What do you want to do to this sprite renderer?

small mantle
#
void Start() {

        rb = GetComponent<Rigidbody2D>();
        rb.velocity = new Vector2(bulletSpeed, rb.velocity.y);

        DestroySelf();
    }``` This is the Spear Script
final kestrel
#

Action is a void return type delegate?

swift crag
autumn tusk
rich adder
swift crag
final kestrel
#

hm I kind of got confused what does public static event Action OnSomething mean?

summer stump
swift crag
#

The weapon is just a thing that holds some stats and a sprite?

rich adder
#

Action is just a delagate with no return value / void @final kestrel

swift crag
#

Okay, so just give the weapon class a Sprite field

#

Or you could give it a Sprite property, which would work like this:

#
[SerializeField] SpriteRenderer spriteDisplay;
public Sprite WeaponSprite => spriteDisplay.sprite;
final kestrel
swift crag
#

spriteDisplay is the sprite renderer on the weapon on the ground

hybrid gust
#

Any way to destroy all the children of a game object? I keep getting errors about dependencies in the child objects I want to destroy.

{    internal void RecreateGrid()
    {
        foreach (var child in transform.GetComponentsInChildren<Transform>())
        {
            if (child == inventoryTilePrefab) { continue; }
            DestroyImmediate(child);
        }

        for (int x = 0; x < xTileCount; x++)
        {
            for (int y = 0; y < yTileCount; y++)
            {
                Instantiate(inventoryTilePrefab, transform);
            }
        }
    }

}

[CustomEditor(typeof(InventoryGrid))]
public class InvnetoryGridEditor : Editor
{
    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();
        InventoryGrid grid = (InventoryGrid)target;

        if ( GUILayout.Button("Regenerate Grid"))
        {
            grid.RecreateGrid();
        }
    }
}```
swift crag
#

WeaponSprite is a property that returns the spriteDisplay's sprite.

rich adder
swift crag
turbid bridge
#

ok so as you see i have a string which is the first text in the red box but if you look at the second red box i have 2 of the same things one being a string and i dont know what the other is but when i look through the coding i cant work out what im missing. this is the last thing i need to fix for tonight if anyone can point out what im doing wrong. https://hastebin.com/share/cuyewalive.csharp https://i.imgur.com/sbxU2v2.png

swift crag
#

But I use them anywhere I need to get a result back.

#

Consider the following:

final kestrel
small mantle
# rich adder this gives no context.. You have to show also how you make bulletSpeed occur

This is the Spawn Script when the Gob gets close to Player. ```cs
void Update() {

    attackTimer = attackTimer + Time.deltaTime;

    if (enemyFollow.canAttack && attackTimer > attackCooldown && !enemyFollow.canMove) {
        Instantiate(spearPrefab, throwPosition.position, Quaternion.identity);
        attackTimer = 0f;
        enemyFollow.canMove = true;
    }

}```

This is the movement Script but only the Flip code for Gob ```cs
void Flip() {
facingRight = !facingRight;
transform.Rotate(0f, 180f, 0);
}

}```
swift crag
rich adder
swift crag
#

This method takes a function that takes a T and returns a V

#

I called it "metric" because it's the metric I'm using to compare values

#

So it calculates a value for each item, then compares those values, then returns the item with the lowest value

final kestrel
#

oh okay

final kestrel
swift crag
#

You use System.Action when you're performing..an action!

swift crag
#

i really need to figure that out sometime soon

#

now that we have that Awaitable doohickey

rich adder
swift crag
#

System.Func is used when you need a mathematical function: something that maps from a domain to a range (:

autumn tusk
small mantle
#

I think I know the solution. I just need to have the Spear know what rotation the Enemy is at its spawn initiation. How could I do that?

autumn tusk
swift crag
summer stump
swift crag
final kestrel
#

a function that returns Task. async is used to perform tasks asynchronously yes but I never had to use it so I'll probably wont get what this means till I use haha

swift crag
#

You can reference the spear prefab as a Spear (or whatever you named the component) instead of as a GameObject

#

That way, you can just do:

small mantle
swift crag
#
Spear spear = Instantiate(spearPrefab);
spear.startRotation = transform.rotation;
rich adder
#

of the player

small mantle
#

I'll try

rich adder
#

pretty much what Fen wrote above there, or do it Inline the Instantiate method

final kestrel
#

I have a somewhat simple question. How do you manage the scripts? Do you follow solid principles or just try to follow and yeet the rest?

swift crag
#

too abstract!

summer stump
rich adder
swift crag
#

One of my main objectives is to get rid of nasty coupling

final kestrel
swift crag
#

things that surprise me when I try to extend my code

rich adder
#

you're trying to DestroyImmediate on the Transform component @hybrid gust

#

not possible

final kestrel
summer stump
#

That doesn't violate SOLID

hybrid gust
#

Ah, I shoudl reference the gameobject itself and not the transform then?

#

I didn't even think of it like that

summer stump
swift crag
#

imo

final kestrel
#

you either have props or methods in a class

swift crag
final kestrel
#

Ah okay

summer stump
swift crag
#

where did you read this?

#

this isn't even the single responsibility principle

rich adder
final kestrel
#

Uhh i read it somewhere

swift crag
#

that sounds like...the single-kind-of-member-principle, which I just made up

queen adder
#

Haha

hybrid gust
summer stump
final kestrel
#

Could be yeah. Well

swift crag
#

a core tenet of object-oriented programming is to create objects that hold both data and logic

queen adder
#

I think its best to learn SOLID thru fucking up

summer stump
#

SRP means everything should be part of a single responsibility.
In your health example, you would have things like variables CurrentHealth, MaxHealth etc and methods like ReduceHealth etc
Health class has the responsibility over health

swift crag
#

make a game, find out what blows up in your face, and learn from that

turbid bridge
final kestrel
#

I learn everything through fucking up so thats a good idea

queen adder
#

Once u have extremely spaghetti code youll appreciate what SOLID tries to do

small mantle
rich adder
queen adder
#

Its kind of hard to understand SOLID unless you actually mess something up

swift crag
#

I'm guessing you have a component that you attached to the spear

#

I decided to call it Spear

rich adder
small mantle
queen adder
#

Diamond whats the error?

small mantle
queen adder
#

Also Berkay learn about interfaces

#

Best thing to learn IMO as a beginner

hybrid gust
#

speaking of fucking up. I just deleted an object i didn't want to because GetComponentsInChildren also includes the parent of those game objects apparently

rich adder
final kestrel
#

I learned some stuff on a web development course. Abstractions interfaces why they help you write loosely coupled code and all but when I'm working on a game. I just aim for shit to work. This is probably normal right? šŸ˜„

swift crag
queen adder
#

@turbid bridge whats the error?

swift crag