#💻┃code-beginner

1 messages · Page 486 of 1

sturdy wyvern
#

worst part is that this was working a second ago but when i accidentally closed unity the whole thing broke Death

ebon ore
#

not sure im doing it correctly, i've created "Resources" folder in my "Assets" folder, then i've put the json files in it.
then in code:
string jsonString;
TextAsset jsonFile;
jsonFile = Resources.Load<TextAsset>("levels5.json");
jsonString = jsonFile.text;

#

and im getting object reference not set to an instance of an object

slender nymph
teal viper
#

Ah, I guess, a json file is fine too.

ebon ore
#

removing ".json" fixed it, thank you guys ❤️

sturdy wyvern
#

....im stupid. the spawn points' box colliders were still onnnn 😭 here i was confused out of my mind when the solution was literally one button click. notlikethis

faint osprey
#

        var emitParams = new ParticleSystem.EmitParams();
        emitParams.position = (mousePos + Random.insideUnitCircle.normalized * 0.3f);
        cosmicDustTap.Emit(emitParams, clickPower);```
if say my clickpower was 2 in this scenario the particles would just spawn in the same position so I wouldnt see them right
vestal adder
#

how can i check if my game is optomised when my pc is above average

#

so when i do bad code and such i may not notice since it wont strain mah system

tender stag
#
player.position = Vector3.SmoothDamp(player.position, vehicleSeats[targetSeatIndex].seatPosition.position, ref positionVelocity, enterDuration);
player.localRotation = Quaternion.Slerp(player.localRotation, Quaternion.identity, enterDuration);```
#

how do i make the smootdamp and slerp run at the same speed?

#

so they both finish at the enterDuration

#

i need them to both finish at the same time

rich egret
#

Vector3 itemPosition = newItem.transform.position;
Quaternion itemRotation = newItem.transform.rotation;

newItem.transform.SetParent(targetTransform, false); // false ensures world position stays the same

ewItem.transform.localPosition = itemPosition;
newItem.transform.localRotation = itemRotation;```

This should create a **child** and bring it to its **parent** but still keep the `original location`.
The child moves to `another location` (not the original location) how can this be solved? 🤔
faint osprey
#
        {
            foreach(GameObject G in upgradeCardQueue)
            {
                Instantiate(G, panel.transform);
                upgradeCardQueue.Remove(G);
            }
        }```
this is giving me errors however its working as intended am i good to ignore it
slender nymph
languid spire
#

also you are using a world position to set a local position

slender nymph
faint osprey
slender nymph
#

an exception will cause any code that should run after the exception to not run. so if an exception is thrown in the first iteration of the loop it won't reach the second

faint osprey
#

so then how did it

slender nymph
#

if you're just going to remove everything from the list, just use List.Clear after the loop

tender stag
#

the smoothdamp is fps independent

#
player.position = Vector3.SmoothDamp(player.position, vehicleSeats[targetSeatIndex].targetExitPosition, ref positionVelocity, exitDuration);
player.rotation = Quaternion.Slerp(player.rotation, Quaternion.identity, exitDuration * 1.5f);```
#

but the slerp is fps dependent

#

how can i make it so that the slerp is fps independent and finishes at the same time as the smootdamp?

nova solstice
#

i am a COMPLETE beginer to unity and real coding in general can anyone tell me good tips and cways to learn atleast the basics?

eternal falconBOT
#

:teacher: Unity Learn ↗

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

nova solstice
#

!learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

ivory bobcat
eternal falconBOT
nova solstice
ivory bobcat
nova solstice
#

ok

ivory bobcat
#

Reminder that Unity API (written in c#) isn't regular ol c# so you'll get better responses here in #💻┃code-beginner

nova solstice
#

oh

#

whats different about it?

covert owl
#

Understanding packages is not the issue,
All I'm trying to figure out is when I make a grid, how do I make is so I can build on said grid

ivory bobcat
teal viper
covert owl
#

What?

teal viper
#

There is not default "building" functionality in unity.

#

You need to write it.

covert owl
#

Yhea I know that, but I'm trying to find a good example that explains what's going on

#

One that dosen't have code pop out of nowhere

#

Or requires me that download something

teal viper
#

What kind of code? Tutorials usually explain the relevant code. Otherwise there wouldn't be a point in them.

#

If you have a specific example, share it.

covert owl
#

I don't have a specific example

#

All I'm asking for it be directed to a video or document just something that can tell/show me how to build on a grid

#

Like place buildings and stuff

teal viper
ivory bobcat
covert owl
covert owl
teal viper
stiff fjord
#

i would like to allow the player to edit the controlls in a menu and i need help with creating a variable that can be used in Input.GetKey(KeyCode.variableName) and i would like 1 script with every variable name like a dictionary so i was wandering how i would go about accessing that across diffrent scripts heres what i got rn

covert owl
teal viper
rich adder
stiff fjord
rich adder
languid spire
weak cedar
modest dust
# covert owl Like place buildings and stuff

Break down your problem into smaller steps and tackle them one by one. There might be a tutorial which explains exactly the system you want to make or (more probable) there might be not. If after thorough searching you can't find one which satisfies you, there probably isn't any that will. Find one which is similar enough to what you want to make, watch it, understand the general idea behind it and adjust to your own requirements.

rich adder
#

just use the new input system thinksmart

weak cedar
languid spire
weak cedar
languid spire
rich adder
covert owl
rich adder
languid spire
weak cedar
#

int, enum[]

#

he could assign ints for every direction

#

but I doubt if this would be useful

languid spire
stiff fjord
weak cedar
#

If he won't use the new input system, what could he do?

languid spire
covert owl
stiff fjord
weak cedar
jade tartan
#

@Niktu @gr4ss Indeed, the tuto forgot to tell me that, thank you very much!

fading hazel
#

hi can i ask a question here

weak cedar
weak cedar
rich adder
eternal falconBOT
stiff fjord
teal viper
weak cedar
faint osprey
#

emitParams.position = Random.insideUnitCircle * 7;
is there a way to make .insideUnitCircle have a minimum value so say the radius maximum is 1.0 but the minimum is 0.3 for example

weak cedar
#

or use singletons

teal viper
lapis frigate
#

yo @teal viper can I ask you something?

teal viper
#

Don't ask to ask

lapis frigate
#

ok

#

anyway if u remember when u give me like an example of how diffrent enemy behavior should look like in my script it was something like this

#

I cant make the unit class abstract

#

because then I cant get it into the enemyLibrary array

teal viper
lapis frigate
#

if I do its clears my library

#

and I cant drag it back

teal viper
#

Wdym "clears"?

lapis frigate
#

by it I mean the enemy prefabs

#

it makes the elemnts "none"

teal viper
#

You should be able to drag in any prefabs that have components deriving from Unit

lapis frigate
#

well I cant and idk why

teal viper
#

Share your code and prefab setup

lapis frigate
#

I didn't changed anything yet cuz I got stack in the unit scrip

#

but ok

teal viper
#

Well, then what did you try to drag into the array?.

lapis frigate
teal viper
#

You can't have Unit components, as they're abstract.

lapis frigate
#

this is my unit script

teal viper
#

Okay. And what do the prefabs have?

lapis frigate
#

an example

#

the behavior script is empty tho

#

if I cant drag them as units what should I do

#

because its just makes sense for the enemies to be units

teal viper
#

That script would go on the prefab and not Unit

#

Then you will be able to assign it in the array as well

lapis frigate
#

I dont get it

stiff fjord
lapis frigate
#

I need to create a new unit script for each enemy?

teal viper
lapis frigate
#

ok but what wil decide the stats

#

if I cant drag the unit script

teal viper
lapis frigate
#

so I need to save the behaviour and the stats at the same script?

teal viper
#

Yes.

lapis frigate
#

so like I shoud create a game object then create a script for it and make it Unit : Goblin

#

and then write the stats and the behaviour there?

teal viper
#

I mean, you can make it more complex, separate data and behavior and make it as complex as you want. But seeing how you have issues with even a simple setup like that, maybe don't overcomplicate it for now.

teal viper
lapis frigate
teal viper
lapis frigate
#

so I need to remove the unit script and create a new script that inheriet from the unit script?

teal viper
#

yes

lapis frigate
#

ok i will try that and if I will have problems (and I will) I'll cry for help later

#

tnx though

faint osprey
#
        {
            var emitParams = new ParticleSystem.EmitParams();
            for (int i = 0; i < CDPS; i++)
            {
                var randomDirection = Random.insideUnitCircle;
                var randomDistance = Random.Range(3, 7);
                emitParams.position = randomDirection * randomDistance;
                cosmicDustTap.Emit(emitParams, 1);
                dustCount += 1;
                massCount.text = ((double)dustCount / SolarMassConversion).ToString() + " Solar Masses";
                IncreaseStarSize();
                float time = 1 / CDPS;
                yield return new WaitForSeconds(time);
            }
            yield return null;
        }```
im trying to spawn a particle in a random location based on particles a second which is the CDPS variable and im trying to make it look like they spawn 1 by one by delyaing it with the time float however I dont know what to put after the for loop as having nothing will lead to an infitine loop which unity wont run and having yield return null makes everything happen really fast and not in time
slender nymph
#

is CDPS an integer

faint osprey
#

good question

#

ah yes

slender nymph
#

yes, so integer divided by integer results in an integer. 1 divided by anything other than 1 is 0

faint osprey
#

that makes sense

teal viper
faint osprey
#

but it still gives me one

faint osprey
slender nymph
#

you are still constrained to the timing of your framerate, so if CDPS is so high that the time it waits is less than the time it takes for one frame to pass, then you'll end up with fewer iterations of the loop than you would expect

faint osprey
#

yeah that makes sense

faint osprey
stiff fjord
weak cedar
slender nymph
# faint osprey would the way around that be just doing everything that i do in the loop with a ...

I'm not sure I get what you mean by that. But my typical recommendation to get around that restriction would be to use a manual timer rather than WaitForSeconds. So you just increment a variable by deltaTime each frame, then when it goes past your time threshold you perform the action(s) required and subtract the time threshold from it in a loop until it has gone below the threshold again. Kind of like this:

private float _timer;
private void Update()
{
  _timer += Time.deltaTime;
  while(_timer >= _waitTime)
  {
    _timer -= _waitTime;
    DoAThing();
  }
}

it will still be a bit inaccurate, but will accumulate those extra seconds caused by longer frame times so that it can still perform the expected number of actions in the expected time frame (or as near to it as you can possibly get)

shy tiger
#

How to fix this problem?

teal viper
shy tiger
teal viper
#

Well, then where did you get that code from?

#

What's the intention behind it?

shy tiger
teal viper
steep rose
#

you need to make it a method as stated in the error stack trace

#

or just use docs to find out your answer

teal viper
# shy tiger

Compare the like in your code with the one in the tutorial carefully.

lapis frigate
#

yo dlich the ememy Units the inheriet from the Unit class shouldn't be abstarct too right?

teal viper
#

The derived classes shouldn't be abstract, no.

lapis frigate
#

but when I create it as like:
public class GoblinUnit : Unit
{

}
I get compiler error

teal viper
#

What error?

lapis frigate
#

CS0534

teal viper
#

I don't memorize error codes...

#

humans don't memorize error codes

lapis frigate
#

'GoblinUnit' does not implement inherited abstract member Unit.Act()

#

ye I know just copied the error too

teal viper
#

The error is pretty much self explanatory

lapis frigate
#

i know

teal viper
#

it tells you that you need to implement the Act method

lapis frigate
#

but when I do inheriet it it wont go away

#

im not that stupid but its still wont go away

#

and then I get another warning

teal viper
#

Then you don't inherit it correctly. Try opening the suggestions next to the underline. It should have a suggestion to implement the abstract class.

lapis frigate
#

should I useo verried or something?

teal viper
#

verried?

lapis frigate
#

overried

#

override

#

omfg

teal viper
#

No. That's for overriding methods that are already implemented in the base class.

lapis frigate
#

so why it says I didn't impimented it even tho I did

teal viper
#

If it says that you didn't, then you didn't.

lapis frigate
#

I guess I didn't then

teal viper
#

Share the base class code.

lapis frigate
#

the unit u mean?

teal viper
#

Yes.

lapis frigate
#

I didn't use inheritence in ages

teal viper
#

This should work.

#

Do you actually get an underline in that script?

lapis frigate
#

yes

teal viper
#

Take a screenshot of your ide

lapis frigate
lapis frigate
teal viper
#

Hmm... Maybe you do need the override keyword🤔

lapis frigate
#

Idk man

#

im lost here ill do what u think atm

#

well it did fixed it

teal viper
#

Yeah, you do need it. Confused with interfaces.
Anyways, next time just use the ide suggestion to autoimplement it.

lapis frigate
#

ok

#

now it gives me an error when I try to load the game

teal viper
lapis frigate
#

ye I guess

#

its the setup battle method

rich adder
lapis frigate
#

ye but I didn't change anything in the code

rich adder
#

this isnt the script

#

dont you see the name is different

#

Whatever is on line 17 in BattleHudScript is null

#

You can't access an object when its null

lapis frigate
#

when I click on it it doenst even send me to the battlehudscript tho

rich adder
#

is your IDE configured correctly?

lapis frigate
#

it sends me to the battlesystem script

#

I'm pretty sure it does

teal viper
rich adder
#

check external tools and maybe regen project files

#

also this what dlich said ^^

#

the link I sent you shows how to break down the stack trace

teal viper
#

At some point you'll find that you'll need to dig into the stack trace to find the actual cause of the error.

lapis frigate
#

ok just 1 more question

#

when I changed the array from Units to Scripts that inheriet from unit I needed to change the way I get the gameobjects from the array?

teal viper
#

That's the whole point. There's no point in changing it to the derived types.

lapis frigate
#

so I have no idea what is the problem

#

I think the battlehuscript is null because whatever is in the enemyUnit is null

rich adder
#

can you show what the line / script is its throwing null on

teal viper
lapis frigate
#

I sent it already

#

1 sec

lapis frigate
rich adder
#

you sent BattleSystem

#

thats the wrong script as I already explained to you

#

did you not read anything said lol

lapis frigate
#

I did

rich adder
#

so why did you sent the wrong script again

#

the error tells you exactly which line threw the error in which script

lapis frigate
#

but where it says and where it throws me is diffrent

rich adder
#

doesn't matter, thats just unity being weird

#

read the actual errors thats all that matter

teal viper
lapis frigate
#

thats the battlehuscript

rich adder
#

nameText is null

lapis frigate
#

ye I get that

rich adder
#

so assign it

lapis frigate
#

I think its null because the enemyUnit is null

#

its assinged in the inspector

rich adder
#

its null because TMP_Text is not assigned to a component

rich adder
lapis frigate
#

I think its not just name text

rich adder
#

either its assigned properly and gets unassigned at runtime somehow, OR you have a copy with it unassigned

lapis frigate
#

Name text is the first line that I make use in the enemyUnit information in the code

#

I think its null because enemyUnit is null

#

I just dont know why

rich adder
#

are you passing a null then ?

lapis frigate
#

I dont know why its null though

rich adder
#

where do you call SetHUD

lapis frigate
#

in the setup battle method in the battlesystem script

teal viper
#

You can add a debug log in that method and see what exactly is being null

rich adder
#

should've read the whole stacktrace

lapis frigate
#

I just try to understand why the enemyUnit is null

#

I changed the array to gameobjects that inheriet from unit

#

instead of Units

#

and then its became null

teal viper
rich adder
#

ur assigning a prefab

lapis frigate
#

yes

rich adder
#

you never actually instantiated a gameobject did you

lapis frigate
#

umm no...

rich adder
#

thats prob why its null

lapis frigate
#

so where should I instantiate it

rich adder
#

GameObject playerGO = Instantiate(playerPrefab, etcc.

#

same thing with enemyGo

#

if you assign the one from the inspector, whatever happens to that one in the inspector keeps getting cloned

#

eg if you destroyed it then everyone clones a null ref

#

or if its a prefab then you get weird behaviors because its not a clone but the same one, when you do = on a reference type unless you create a new instance you're passing around the same reference

lapis frigate
#

but why I didn't had to instantiate the previous gameobject

#

when it was unit

weak cedar
#

I’m using a tweening library. There are methods such as move, rotate and scale. Should I have seperate scripts for each or have a single script where I decide which method to call with an enum, which one would be better performancewise

rich adder
#

GetComponent<Unit>(); do you have a Unit component on enemyPrefab

lapis frigate
rich adder
#

when is that run because enemyUnit = enemyGO; here is in Setup GameObject playerGO = playerPrefab;

lapis frigate
#

at the started I did enemyGO = enemiesLibrary.enemiesLibrary[i];

rich adder
#

I dont see anywhere you assigning a UNIT component to your enemy

lapis frigate
#

and then enemyUnit = enemyGO

lapis frigate
rich adder
teal viper
rich adder
#

enemyGO = enemiesLibrary.enemiesLibrary[i];
I don't see any logging here so you're assuming this if statement even hits ?

#

or that it has the component ?

lethal meadow
#

bool IsObjectInView(Camera cam, Transform obj)
{
count = 0;
Plane[] planes = GeometryUtility.CalculateFrustumPlanes(cam);
foreach (GameObject child in obj.GetChild(0))
{
if (GeometryUtility.TestPlanesAABB(planes, obj.GetChild(0).GetComponentInChildren<Collider>().bounds))
{
count += 1;
}
else continue;
}

    if (count > 0)
    {
        return false;
    }
    else
    {
        return true;
    }

}
rich adder
#

and ideally when you found wat you're looking for you break out early from loop

rich adder
lethal meadow
#

i forgor

#

same thing

#

im trying to see if any of the child elements have a collider that are in the cameras view

#
    bool IsObjectInView(Camera cam, Transform obj)
    {
        {
        Plane[] planes = GeometryUtility.CalculateFrustumPlanes(cam);
        return GeometryUtility.TestPlanesAABB(planes, obj.GetChild(0).GetComponentInChildren<Collider>().bounds);
    }
    }
teal viper
eternal falconBOT
lethal meadow
#

this was the old version but only worked with the first collider

#

so the hand

#

i need to scan all the colliders

#

idk how

steep rose
#

make an array

#

and scan through all of the children of your character

#

and grab their colliders

inner quartz
#

Hey guys, please help me with this problem:
I got playerData here (photo 1), but it don't equal to this data (photo 2). That's why I can't load my saved data

teal viper
inner quartz
teal viper
# inner quartz

You don't need to share the same screenshots twice. That doesn't help.

inner quartz
teal viper
inner quartz
#

I know why it's equal 0, but I don't know resolution

teal viper
#

Why is it equal 0?

inner quartz
# teal viper Why is it equal 0?

As you can see, in arguments public PlayerData(Values values) I have my Values script. But this currencies in Values script is firstly template and after loading data my data

teal viper
inner quartz
teal viper
#

English! Do you speak it? Explain what you mean in words. We don't need to play a guessing game here...

steep rose
#

well if multiplier is 0, it will always be 0

#

you are working with multiplication here

inner quartz
#

I got here 50, but I need to transfer it to my PlayerData script, where it is equal 0

inner quartz
teal viper
#

Is it serialized as 50?

inner quartz
teal viper
#

Ok, so it's not 0??

inner quartz
#

but in playerData script it equal 0

#

So I need it equal 50

teal viper
#

What is load data script..?

steep rose
#

are you loading it?

hallow acorn
inner quartz
teal viper
inner quartz
faint osprey
#

gameObject.transform.position = new Vector3(700, 0, 0); im setting the transform of this object when i click on it however the transform is changine to 75000 something instead of what i set

steep rose
#

is your object a child of something?

faint osprey
#

yes

steep rose
#

use localposition

faint osprey
#

ah

teal viper
# inner quartz

Aight, here's what we're gonna do: you're gonna put a lot of verbose debug logs in your code and share the output in the console log. Until you can do that we have no freaking clue what you're trying to say.

ancient karma
#

looking for some feedback on this script https://pastebin.com/DGHZ0snG (too big for a discord embed).

Something in here is killing performance, specifically relating to opening/closing the door. While pressing the interact key on an unlocked door I get a momentary freeze. It's probably something simple which I just dont have a deep enough understanding of unity to see yet.

I'm also open to just general criticism. I rewrote this once already because the old version needed every kind of door to have its own script, so this is my first pass at consolidating. It might suck, feel free to tell me if it does (please tell me why it sucks so I can learn)

teal viper
slender nymph
ancient karma
#

I LEFT THAT IN?

#

oh my lord

steep rose
#

seems like it

ancient karma
#

I was explaining scope and memory allocation to someone and used that as an example. I have made myself a fool

slender nymph
#

lmao just randomly allocating over 3gb every few seconds when you press F

teal viper
# inner quartz

Noooo. Not like that.
Verbose logs. I have no freaking clue what these numbers represent. Add some text explaining that in the log.

inner quartz
hallow acorn
teal viper
teal viper
teal viper
#

And make sure you understand what type transform.rotation is.

teal viper
eternal falconBOT
lethal meadow
#

my raycasts aint working and ive got no clue why

#

never had this happen

#

UnityEngine.Vector3 targetDirection1 = playerBody.position - raycastPoint.position;
RaycastHit hit;

    if (Physics.Raycast(gameObject.transform.position, targetDirection1, out hit, 20f))
    {
        active = true;
    }
#

so it sends a raycast with 20 length out to the player

#

but even when theres literally a massive wall between the player and the enemy it still comes back true

#

wait im stupid as fuck hold on

inner quartz
eternal falconBOT
lethal meadow
#

how do i make raycasts visible again

teal viper
steep rose
lethal meadow
#

where do i enable gizmos

teal viper
steep rose
#

in the game view

inner quartz
# inner quartz Just like this?

Although no, it's not like that. I still have, in fact, the most important question, how to "assign" my saved values to template

teal viper
#
Values class
{
   private PlayerData playerData;
   
   //Any method that you need access to player data
   void Update()
   {
      someData = playerData.someData;
   }
}
inner quartz
lethal meadow
#

so its going below me

teal viper
inner quartz
rigid pike
#

Is there a quick way to disable both Intelicode and Co-pilot with like 1 or 2 settings? (not logging out or any other weird things)
using VS 2022 atm, not code

teal viper
inner quartz
teal viper
rigid pike
teal viper
teal viper
#

This is a different script and is unrelated to assigning playerData in your Values class.

inner quartz
teal viper
#

Not this code.

#

You need to assign a value to the playerData field

inner quartz
teal viper
#

Nothing. It's irrelevant at the moment.

#

Anyways, I'm off to sleep, but I suggest you do proper learning !learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

lapis frigate
#

well I debugged it and I know now for sure that the enemyUnit isn't null when I start the game and so are the enemyName, enemyLevel ect. and I still have no idea why I get an error

bold iron
#

im having problem alligning my text with a object (in my case being a chest). i want to make it float on top of the chest but when i reset both position to 0 they are way too far apart. And the scale doesn't match too as my text appears ginormous while my chest is tiny. Is there any way to allign the text and the chest?

deft grail
bold iron
deft grail
bold iron
deft grail
bold iron
#

thanks, now another problem is how to a allign it?

deft grail
bold iron
rocky canyon
#

might be helpful to know for future things.. idk

#

i do this especially when im making world canvas because they start out soo big and are usually way off-center of the thing im adding it to... so i move my little gameobject into position and then create it

wintry quarry
#

You could use a world space canvas

#

Or you could use 3d game world text

haughty reef
#

Hey! How could I make a mouse sensivity slider?

wintry quarry
#

With a UI Slider component

celest flax
#

I have a coroutine where I want to check if any enemies are currently alive, and go to the next wave if there are not. Is there a good way to do this? I could do it in update but if possible I'd prefer to do it in the coroutine. I tried using a while-loop but found out the hard way that didn't work

languid spire
rich adder
#

You should have an event, enemies register themselves to enemy manager. When enemy dies it fires the event and removes itself from List on enemy manager, when list reaches 0 then you know they're all dead (check each time enemy removes from list)

celest flax
rocky canyon
#

wait.. j/k?

languid spire
#

or

int enemiesAlive;
int EnemiesAlive { get {return enemiesAlive;}
 set {enemiesAlive = valie;
      if (enemiesAlive == 0) NextWave();
}}

void NextWave() { }

@celest flax

jade tartan
#

Hi, it's me again, sorry, I'm still following turorial for making a 2D videogame and I facing another problem : I tried to program a deathzone who redirects you to the PlayerSpawn area when you fall in it but instead my character just keep falling across. I did follow the programming and activated the IsTrigger case, put the Tag asked, but no result, Can someone help me? I'll put the link of the video (Warning : It's in French) https://youtu.be/5MmX3Mea29Y

Aujourd'hui on regarde comment ajouter des zones d'élimination dans nos niveaux. Cela nous permet notamment d'éliminer le joueur s'il tombe dans le vide ou se rend dans une zone inaccessible.

☕ Soutenir la chaîne ☕
➡️ sur Tipeee : https://www.tipeee.com/tuto-unity-fr
➡️ sur uTip : http://utip.io/tutounityfr

📥 Télécharger le projet de la série ...

▶ Play video
rich adder
#

also when you link a video you should link to the specific timestamp that sets this up

jade tartan
#

Sorry, here are the screenshots, I'm not sure which timestamps would fits the proper time but the creation of the Deathzone takes the first half of the video.

rich egret
#

bcs its not work for me

rich adder
#

look at the video then compare what you got and let me know

cosmic dagger
ivory jasper
#

if i were to have an object that could instantiate many different kinds of objects, would i need to create a reference for every single object?

rich adder
ivory jasper
#

like the prefabs right?

rich adder
#

yea prefabs for example

ivory jasper
#

would i need a reference to each prefab?

rich adder
#

you could potentially use Resources and maybe use names , you still have to differentiate them somehow

#

having references to prefabs for each one in the inspector is the most straight forward way usually

#

it really depends on the project too tbh

willow scroll
ivory jasper
#

im not sure if i know how to do that

willow scroll
# ivory jasper im not sure if i know how to do that

That's what I thought upon reading your message. You have to add a prefab to the List on spawn

[SerializeField] private GameObject objectPrefab;

private System.Collections.Generic.List<GameObject> _objects;

private void InstantiateObject()
{
    GameObject newObject = Instantiate(objectPrefab);
    
    // ...
    
    _objects.Add(newObject);
}
rich adder
willow scroll
bold iron
jade tartan
rocky canyon
bold iron
#

also

#

how do i get out of this thing? 😅

#

anyway as you can see

rocky canyon
#

double click the Game word

bold iron
#

i manage to allign the text with the chest so its fine

rocky canyon
#

the one with the controller next to it

#

or hover the entire window and press Shift + Space

#

thats the quick way to mini-maxi every window

bold iron
#

it worked!

rocky canyon
#

another thing that might save you some time.. is you can set the default Font of new text mesh pro elements

bold iron
#

oh interesting. i will definitely apply it thanks

rocky canyon
#

as well as a few other options.. but its really useful to just have it already set up to the font ur using for the majority of ur UI

#

boom.. no more Liberation w/e it is

bold iron
#

now all i need to do is to make the pointer on the chest go up and down

rocky canyon
#

DoTween 😉

rocky canyon
#

it'll force it to redraw all the time..

#

actually im not sure if that applies to the world canvases.. but even if it doesn't
using a tweening library is soo much easier / powerful to do little animations like that

bold iron
#

by regular animation do you mean rigidbody.velocity?

rocky canyon
#

no.. i mean the animation/animator windows

bold iron
#

oh i was planning to actually move it up and down

rocky canyon
#

w/ code?

bold iron
#

yes

rocky canyon
#

ohh yea thats the better route 👍

#

thats what DoTween does..

#

its just a library that already has all these premade functions

bold iron
#

i see

rocky canyon
#

like Bob, Shake, Twirl, Rotate, etc

#

those arent the actual method names.. but its just simple stuff

#

DOTween is the very first thing I install upon creating a new project. Animate your position, rotation and scale in a single line of code, with all the customization you could hope for... and that's only scratching the surface.

For the full documentation: http://dotween.demigiant.com/documentation.php

❤️ Become a Tarobro on Patreon: https://ww...

▶ Play video
#

@bold iron just in case you want to look into it now or later ^ heres a decent run-down of it

bold iron
#

ok, saved 👍

#

also, i have a question regarding my dashing ability. Is there a function that make your character go to point a to b with a certain speed instead of just teleporting it point a to point b?

rocky canyon
#

are you using a Rigidbody2D for movement?

rocky canyon
#

you should avoid using translation at all then...

#

transform.position = blabla;

#

thats always teleporting.. you should instead use the physics methods to move the rigidbody..

#

rb.velocity = , rb.AddForce, rb.MovePosition, etc

bold iron
#

oh, that was exactly what i did but it looked like teleportation

rocky canyon
#

can you show the !code you have for your movement / dash

eternal falconBOT
bold iron
#

okay

#

ive saved

rocky canyon
#

noo.. lol thats just an embed telling you how to properly share code in any of these channels

#

the links for example.. chose one.. (paste ur code into it and press the save icon)
the URL should then change..

#

just copy and paste that URL here.. and we'll be able to look at the code

bold iron
#

ohhh, ive never used these tools sorry

rocky canyon
#

no worries.

bold iron
rocky canyon
#

looks correct from just that part

#

rb.velocity ur setting the velocity of the rigidbody..

#

that code doesn't actually teleport the rigidbody anywhere

bold iron
#

so it just moves the rigid body?

rocky canyon
#

changes its speed/velocity yea

#

the rigidbody moves itself

bold iron
#

so do i still need the iteration?

rocky canyon
#

if u were to say use transform.position = newPosition; that would be a teleportation

#

(and also wouldn't respect collisions/physics

bold iron
#

ok that makes sense

#

i used tranform.position for the animation of the pointer

rocky canyon
#

Each iteration waits for 0.1 seconds before applying the velocity again, creating a staggered dashing effect..

bold iron
#

i tried copying the code of dashing from other people but for some reason it doesn't work because each of them moves the player so fast i cant even see it. So eventually i decided to spend some time making my own dashing

rocky canyon
#

i only warn against using it for physics stuff

#

b/c ur bruteforcing it in a way..

#

u could literally walk thru a wall .. the rigidbody wouldnt stop u.. b/c ur teleporting ur way thru it for example

#

but for other things.. its a fine method

rocky canyon
#

just b/c it doesn't appear to work correctly right out the gate.. doesnt mean its the wrong method

#

when building / prototyping i liek to use public variables and tweek them in the inspector as the game is running..

#

and hten once i find that sweet spot i jot down the new values and change them

bold iron
#

oh so i might not have the correct variables for my rigid body

#

Well thank you for your input

#

I really appreciate that

rocky canyon
#

for Dashing and stuff that has a timer, I usually use a Coroutine

using System.Collections;  // Required for coroutines

private IEnumerator Dash(){
    canWalk = false;
    // Apply dash velocity
    rb.velocity = new Vector2(DashDirection.x * 20, DashDirection.y * 20);
    
    // Wait for the dash duration (e.g., 0.2 seconds)
    yield return new WaitForSeconds(0.2f);
    canWalk = true;
}``` to call: `StartCoroutine(Dash());`

*might be something else you can look into.. (Coroutines are really good to know regardless)
bold iron
#

I see. So it will keep running rb.velocity for 0.2 seconds

rocky canyon
#

it runs in order.. (it wont set the velocity twice only once)

#

after it does that tho.. it'll wait .02 seconds and then set ur canWalk to true..

#

(then ur walking/movement code should set the velocity back to whatever it needs to be)

wintry quarry
rocky canyon
#

and u can add yields anywhere thru-out the coroutine u want..

bold iron
#

Ok

rocky canyon
#

for example..
// do this instantly
// then wait a second
// then do this.
// now wait another second
// finally do this

bold iron
#

ok

bold iron
unkempt bear
#

Respected,
this will call on the particle collision....

  if (_hit.collider.gameObject.name == gameObject.name) 
{   
UIController.instance.UpdateCurrentInteractingObject(objectName);
      Debug.Log("why2: " + hit.textureCoord + "..." + hit.collider.gameObject);
      // If the ray hits the object, returns the texture coordinates of the hit point.
     
 return _hit.textureCoord;
 
 } 

this code works fine in the editor.
but when I export the android build..
it returns the default unity cube texture point correctly on collision... but on other meshes it print the name correctly and always return the (0,0) texture hit points on each part collision of the body.
I have applied my shader, but I think it's not relevant to the shader.
I don't know, I didn't get anything relevant to this..
And i am trying to get the solution from past two days.
Kindly guide.
Thanks

bold iron
#

actually i will jjst try it again

wintry quarry
eternal falconBOT
bold iron
unkempt bear
wintry quarry
unkempt bear
wintry quarry
#

hit.textureCoord only works on MeshCollider

covert owl
#

!code

eternal falconBOT
unkempt bear
queen adder
#

im completely stumped with this, im trying to tilt a transform 45 degrees to the left or right if its close to its respective wall, but for some reason it only rotates in 1 direction regardless of where the wall is.

this is my code, onRW and onLW are booleans defined in another script to show if the player is near either the left wall or right wall, and rightN and leftN are the direction of the walls from a raycast (defined as rayHit.normal)

if(movescr.onRW && !movescr.onLW){
    idk = Quaternion.AngleAxis(45f,movescr.rightN);
}
if(movescr.onLW && !movescr.onRW){
    idk = Quaternion.AngleAxis(-45f,movescr.leftN);
}```

if anyone could please help id really appreciate it
wintry quarry
#

SHow the rest of the code

covert owl
#
using System;
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Tilemaps;

public class NewBehaviourScript : MonoBehaviour
{
    public static GridBuildingSystem current;

    public GridLayout gridLayout;
    public Tilemap MainTilemap;
    public Tilemap TempTilemap;

    private static Dictionary<TileType, TileBase> tileBases = new Dictionary<TileType, TileBase>();

    private Building temp;
    private Vector3 prevPos;

    #region Unity Methods

    private void Awake()
    {
       current = this;
    }


    private void Start()
    {

        string tilePath = @"Tiles\";
        tileBases.Add(TileType.Empty, null);
        tileBases.Add(TileType.White, Resources.Load<TileBase>(path:tilePath + "white"));
        tileBases.Add(TileType.Green, Resources.Load<TileBase>(path: tilePath + "green"));
        tileBases.Add(TileType.Red, Resources.Load<TileBase>(path: tilePath + "red"));

    }


    private void Update()
    {
        if (!temp)
        {
            return;
        }

        if (Input.GetMouseButtonDown(0))
        {
            if (EventSystem.current.IsPointerOverGameObject(0))
            {
                return;
            }
            if (!temp.Placed)
            {
                Vector2 touchPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
                Vector3Int cellPos = gridLayout.LocalToCell(touchPos);

                if (prevPos != cellPos)
                {
                    temp.transform.localPosition = gridLayout.CellToLocalInterpolated(cellPos
                        + new Vector3(.5f, .5f, .5f));
                    prevPos = cellPos;
                }
            }
        }
    }


    #endregion

    #region Tilemap Management

    private static TileBase[] GetTilesBLock(BoundsInt area, Tilemap tilemap)
    {
        TileBase[] array = new TileBase[area.size.x * area.size.y * area.size.z];
        int counter = 0;

        foreach (var v in area.allPositionsWithin)
        {
            Vector3Int pos = new Vector3Int(v.x, v.y, 0);
            array[counter] = tilemap.GetTile(pos);
            counter++;
        }

        return array;
    }


    private static void SetTilesBLock(BoundsInt area, TileType type, Tilemap tilemap)
    {
        int size = area.size.x * area.size.y * area.size.z;
        TileBase[] tileArray = new TileBase[size];

        FillTiles(tileArray, type);

        tilemap.SetTilesBlock(area, tileArray);
    }


    private static void FillTiles(TileBase[] arr, TileType type)
    {
        for (int i = 0; i < arr.Length; i++)
        {
            arr[i] = tileBases[type];
        }
    }

    #endregion

    #region Bluiding Placement

    public void InitializeWithBuilding(GameObject building)
    {
        temp = Instantiate(building, Vector3.zero, Quaternion.identity).GetComponent<Building>();
    }



    #endregion


}

public enum TileType
{
    Empty,
    White,
    Green,
    Red
}

im having an issue where its only placing at (0, 0) and it wont move, is there something off of what i did?

eternal needle
eternal falconBOT
queen adder
slender nymph
#

assuming that by "it" refers to the building you are placing

wintry quarry
covert owl
slender nymph
#

right so it's doing exactly what you told it to do

covert owl
#

that part i understand,
im supposed to be able to move it at this point tho

slender nymph
#

And have you bothered debugging your conditions?

eternal needle
wanton hare
#

void ThrowBall(int direction)
{

   /* If direction = -1 => left
      If direction = 1 => right */

   _ballSpeed += 0.5f; // Increase the ball speed by 0.5 each time it hits the paddle.

   float xVelocity = _ballSpeed * direction;
   float yVelocity = _rb2D.velocity.y;

   Vector2 ballVelocity = new Vector2(xVelocity, yVelocity);

   _rb2D.velocity = ballVelocity;

}

#

hi, i'm trying to recreate the Pong game, but i have a problem with the ball movement, sometimes when the ball hits both paddles, it gets stuck in an infinite loop of bouncing (I added a physics material to the ball and set the bounce to 1). How can I solve this problem?

#

This is the function responsible for the movement of the ball

wintry quarry
wanton hare
#

yes they are

covert owl
wanton hare
#

@wintry quarry

#

this far

wintry quarry
wanton hare
#

I will try to record a video

rich adder
wanton hare
#


   float xVelocity = _ballSpeed * direction;
   float yVelocity = _rb2D.velocity.y + angleOffset;

   Vector2 ballVelocity = new Vector2(xVelocity, yVelocity);

   _rb2D.velocity = ballVelocity;

}

rich adder
#

i recall just basically giving the ball a slight "nudge" when it goes like that

wanton hare
#

like this?

wanton hare
#

between -5f and 5f?

rich adder
# wanton hare What value should I give the angle offset?

maybe I'd do

Vector3 reflectedVelocity = Vector3.Reflect(ballVelocity, paddleNormal);
if (Mathf.Abs(reflectedVelocity.y) < 0.1f){
    reflectedVelocity.y += 0.1f * Mathf.Sign(reflectedVelocity.y == 0 ? 1 : reflectedVelocity.y);
}
ballVelocity = reflectedVelocity.normalized * speed;
#

I dont use physics materials usually esp with velocity, much better to use Reflect method imo

#

obv replace the magic number for the offset

wanton hare
#

i did add a physics material to the ball with a bounciness of 1, so this won't meet the game requirements?

#

should i remove it?

rich adder
#

you can leave it if you want, depends on your game

wanton hare
steep rose
#

thats what it does

rich adder
#

meaning "too horizontal" so add a slight offset

wanton hare
#

I appreciate your help

rich adder
covert owl
#

    private void Update()
    {
        if (!temp)
        {
            return;
        }

        if (Input.GetMouseButtonDown(0))
        {
            if (EventSystem.current.IsPointerOverGameObject(0))
            {
                return;
            }
            if (!temp.Placed)
            {
                Vector2 touchPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
                Vector3Int cellPos = gridLayout.LocalToCell(touchPos);

                if (prevPos != cellPos)
                {
                    temp.transform.localPosition = gridLayout.CellToLocalInterpolated(cellPos
                        + new Vector3(.5f, .5f, 0f));
                    prevPos = cellPos;
                }
            }
        }
    }

this part is supposed to make it moveable

wanton hare
rocky canyon
rich adder
#

I just get weird inconsistent results sometimes

rocky canyon
#

i usually end up needing to use 2 materials and being very critical when tuning the values to get my results

#

i need to start using reflect more often

rocky canyon
rich adder
rocky canyon
#

like a physics material w/ bounciness of 1 should be a perpetual motion machine

#

but thats usually not the case

rocky canyon
rich adder
#

yeah basically

#

very good laser and mirrors system

rocky canyon
#

what with reflect?

#

perfect actually lol

rich adder
#

ye

#

things get interesting when you add loops to the mix for multi mirror reflection

rocky canyon
#

i was once working on a thrid personm game based on lanterns and colors

#

where ud have to mix certain lights to open certain doors

rich adder
#

i was doing a video / tut on it but kinda got lazy lol

rocky canyon
#

relied alot of color blending

rich adder
#

my inspiration was doing doors like this

torpid snow
fierce geode
#

Hey, is it okay to use System.Activator.CreateInstance to create a instance of a class you want to use.

Like i've got a Consumable class
that has a ConsumeEffect variable for what it effect it has when used.
With each unique effect being a child class of the ConsumeEffect class.

Only problem is that I cant assign that script to the variable without creating an instance of it; so that'd mean creating an instance manually for every new consume effect and assigning it manually.

So instead; I thought of just passing in the name as a variable, and using the name to create an instance of the class. But I don't know if thats safe or proper.

torpid snow
#

So i want to add some footsteps into my code, and i have an idea of how to do so but i have no clue how to actually do it. I have 5 different sfx which i wanna change the frequency of and pitch of, depending on if im walking crouching or sprinting.

torpid snow
wintry quarry
fierce geode
#

Ah okay.

#

I'll change it then

wintry quarry
#

If they're monobehaviours you can use a prefab and instantiate it

fierce geode
#

wait

#

they're not monobehaviors.

#

they're just regular classes.

wintry quarry
#

I would probably do something like make an enum

#

and instantiate via a switch

fierce geode
#

or well the ConsumeEffect is a regular class.

fierce geode
#

was gonna have like a get_effect method in the consumeEffect class that would return the specific class needed.

#

I might do the second one just because it sounds a bit safer.

steep rose
# rich adder i first used it on bouncing raycast bullets 😈

i was wondering if thats how raycast bullet bouncing worked, could you also shoot a raycast to the ground and calculate the angle between the ground and the raycast and if it is higher than a specific threshold then dont bounce, but if its lower than spawn another raycast at the raycast hit position with the appropriate angle and length?

#

i feel like thats way more complicated than vector3.reflect 😅

shell sorrel
#

would just Vector3.reflect, and calcualte the angle between the 2 to decide if i want to od the next cast or not

rich adder
#

either do decent amount of trig or use reflect, is no brainier lol

steep rose
#

i guess it seems mine is way more complicated than it has to be

shell sorrel
#

also its not that much math

rich adder
#

is a very "simple" function too

public static Vector3 Reflect(Vector3 inDirection, Vector3 inNormal)
{
    float num = -2f * Dot(inNormal, inDirection);
    return new Vector3(num * inNormal.x + inDirection.x, num * inNormal.y + inDirection.y, num * inNormal.z + inDirection.z);
}```
shell sorrel
#

reflect is very simple

rich adder
#

yup

torpid snow
rich adder
shy ruin
torpid snow
#

I simply dont know how add the stuff, like i can understand the logic but i just dont know enough about code to apply it. Ive searched some tutorials but they are either very outdated, or have notable jank.

rich adder
#

Unity has footsteps example in one of their Starter Assets, its worht checking out

#

iirc they use Sin function

rocky canyon
#

figure out how to piece together code.. how it works structurally and then after that makes sense its just google for help.. and then directly looking up documentation and "seeing thru" the jank in tutorials to figure out what the important bits are

#

then ofc. the pinned comments

torpid snow
#

Uh, gotcha.

rich adder
torpid snow
#

let me check that out

rich adder
#

ehh the new one is probably better

#

if you're new w code it might be too complex, seems over engineered

torpid snow
#

Yeah kinda, i was really hoping to try and build it off of my state machine (Which i got from following a first person controller guide)

rich adder
#

the concept is more or less the same, check the distance traveled and compare numbers. Its pretty much a math problem

torpid snow
#

Would it be less complex to do a timer between steps multiplied by a float (for whether its more or less frequent) and then see if still moving? thats kinda the idea im tryna implement

rich adder
#

a timer could work but it will be jank

#

if you want a proper result you should count distance/steps

shell sorrel
#

would just do it on distnace traveled

rich adder
#

something like footstepDistanceCounter += characterVelocity.magnitude * Time.deltaTime;

#
float chosenFootstepSFXFrequency = (isSprinting ? footstepSFXFrequencyWhileSprinting : footstepSFXFrequency);
 if (footstepDistanceCounter >= 1f / chosenFootstepSFXFrequency)
 {
     footstepDistanceCounter = 0f;
     audioSource.PlayOneShot(footstepSFX);
 }```
#

had this in my old code

shell sorrel
#

i have always done it with distance, or if i have a animation use events in the animation

torpid snow
#

There really aint an easy way to do this sadly ;-;

rich adder
queen adder
#

events would be the easiest

shell sorrel
#

what was just posted is the easy way

rich adder
#

this is FPV (no legs animation i assuming)

#

i think

torpid snow
#

would animation events work even if i dont have animation? (Just using a capsule)

shell sorrel
#

there would be no point

rich adder
#

it can but you mind as well make a timer at that point

shell sorrel
#

just use the distance approach then

rich adder
#

yeah go for distance

shell sorrel
#

i use it with animation events so it syncs perfectly with what people see

torpid snow
#

ah

shell sorrel
#

if you do not have the animation use the distance

#

would take less time to implement then the amont of time we talked about it

torpid snow
#

Ok my minds getting pretty liquid, let me try and figure out the distance thing and circle back if im truly stuck

shell sorrel
torpid snow
#

well im not entirely sure how to just smash that in my current code

#

if i could i would, trust me

shell sorrel
#

its literally just getting the length of your velocity vector adding it to a field every frame and when its above a threashold you reset it to zero and play the sound

torpid snow
#

Clearly i dont know how to do that man, im tryna learn that crap mind you

shell sorrel
#

if you do not have a rigidbody providing velocity you can also just compute it by subtracting the positions between last frame and current frame

torpid snow
#

Well i have an empty object titled "Orientation" which i use for position, i have it referenced in my movement script and if i can figure it out my footstep script

rich adder
#

use its velocity as shown

torpid snow
#

Idk man, i was just following the tutorial the dude provided (except he didnt provide audio apparently)

#

Its just a first person movement tutorial from some youtuber named "dave", its covered slopes, crouching, walking/running, but NOT audio

rich adder
#

alr well its pretty much as simple as the code I sent to get something going, just put it inside a Grounded check (update or fixedUpdate in this case) and while movement > 0

shell sorrel
#

the audio could literally just be its own script though just give it access to the rigibody to get velocity, and give it a way to know if you are on the ground or not

torpid snow
#

i have the orientation already linked to the footstep code, actively trying to deduce the distance thing

rich adder
#

why not describe what part you're having trouble with

torpid snow
#

Specifically how to find when ive passed a certain distance, and then play the audio. I can worry about pitch and random sfx later

shell sorrel
#

the code to do that was posted above

steep rose
#

just use .distance and then compare it to whatever

shell sorrel
#

its just adding it to a variable per frame then in a if statement checking if its greater then a given value

rich adder
#

to keep track of it

torpid snow
#

should i make a float named like distance or smtn?

shell sorrel
rich adder
#

^ yes they're all pretty much floats

#

if you dont have sprint you can simplify it without the ternary ( ? : ) part

#

you basically need 2 in the inspector (1 if you dont have sprint)
[SerializeField] float footstepSFXFrequency = 0.3f //say 0.3f or something to test

torpid snow
#

i have a sprint, but wouldnt it not matter if its distance based? same for crouching, no?

rich adder
#

well it matter because your footsteps would be more frequency if you run, walk/crouch slow/ etc. 😛

shell sorrel
#

read the code, it was only checking it to decide what sound to use

#

well there example was changing it, but for hte most part moving faster will make faster footsteps already

torpid snow
#

And not to be a broken record (really do appreciate the patience) but how do i increase my distance float based on my movement? Still fuzzy on how to actually increase based on the movement

rich adder
#

something like footstepDistanceCounter += rb.velocity.magnitude * Time.deltaTime; for example

torpid snow
#

K lemme try that, lyk how that goes

rich adder
torpid snow
#

currently still trying to get the darn thing to increase, current issue is it doesnt have a RB (its in a seperate script, should i move to my controller?)

rich adder
#

this way you can also pass the Grounded bool

torpid snow
#

Ok its scuffed but i THINK its fine (Taking a SS now)

rich adder
#
bool grounded;
public bool Grounded => grounded;```
same as this btw
```cs
public bool Grounded
{
    get { return grounded; }
}```
#

if(movementScript.Grounded && etc..)

torpid snow
#

In my code i have a public Rigidbody rb;

#

and then also '''cs void Update()
{
distance += rb.velocity.magnitude * Time.deltaTime;
}'''

#

well that didnt fricking work, you get the idea

#

The thing is increasing, and im happy

rich adder
#

you never use it though

torpid snow
#

huh

rich adder
#

also you need grounded, dont increase it if you're not on the floor lol

torpid snow
#

oh right

rich adder
#

also you probably only want to increase it if movement input > 0

torpid snow
#

lemme just move this to my main move script, easier for me

rich adder
#

its probably cleaner later on to do it as you're doing it now

#

all you need is to reference it as shown then expose each thing you need from it

rich adder
torpid snow
#

right right, currently i have it that way just to see if its working

#

also; got it to increase only while grounded (this was much easier as its already got the grounded params in the main code)

#

let me make a thing so it resets when it hits a certain float (for now ill do like 2 because my man moves quick)

rich adder
#

its 1 line

torpid snow
#

idk man ;-;

rich adder
#

top part being in the Movement script, bottom line being the footsteps script 🤷‍♂️

rich adder
torpid snow
#

right, also managed to get the reset working

rich adder
#

you're inadvertently already doing that when doing any . operation

torpid snow
#

oh neat, if it wasnt insanely obvious im very new to this stuff

#

This is what i did:
if (distance >= stepLength)
distance = 0;

and its working like a charm

rich adder
torpid snow
#

For some reason the dude that did my code made his own groundDrag

rich adder
#

because drag acts different in air

torpid snow
#

huh, for now it works so id rather not tinker with it however.

#

But i do see why its better

rich adder
#

i was just showing an example of how you're already accessing members in other scripts

#

doing it from your own is no different

torpid snow
#

ah right, gotcha 👌

#

So wouldnt i just play an audio in the reset code?

#

because it will only play once, i believe

rich adder
torpid snow
#

lmao nice, that being said no clue how to do audio ;-;

rocky canyon
#

audioSource.PlayOneShot();

#

that'll play once ^

rich adder
#

^ its literally in the example code too

torpid snow
#

let me try that 👍

#

The thing is saying that playoneshot dont exist

rich adder
#

looks like you actually missed a step

rocky canyon
torpid snow
rocky canyon
#

you have to reference an audiosource

torpid snow
#

does that work for multiple audios?

rich adder
rocky canyon
#

u can change that parameter thru code whenever u call it

torpid snow
#

i see... lemme google what an audio source is :c

rich adder
#

AudioSource -> Radio
AudioClip -> The Music

rocky canyon
#

its one of these guys

#

boombox if u will

torpid snow
#

oh i see, can i attach multiple clips, or would i need 5 audio sources 💀

rich adder
#

you can swap them

#

but if they are meant to play at same time then you probably want multiple sound sources

torpid snow
#

nah, they hopefully dont play at the same time

#

and how would i swap them, not manually

rich adder
#

the assignment operator =

torpid snow
#

(also once again huge thanks)

rich adder
#

[SerializeField] private AudioClip jumpSound, hurtSound;
as.PlayOneShot(jumpSound)
as.PlayOneShot(hurtSound)

torpid snow
#

the thing is say there aint no overload method for play oneshot

#

i copied what spawn camp put

rich adder
#

there is no such signature that takes 0 parameters

#

it needs a clip

torpid snow
#

what

#

it has an audio clip in the inspector..?

rich adder
torpid snow
#

With my spare change :<

rich adder
#

you won't get very far without it

#

also its all free all you need is time

torpid snow
#

but the thing has a dang clip in the inspector???

shell sorrel
#

play one shot sets a new clip and plays it once

rich adder
#

a method signature we're talking about here @torpid snow

shell sorrel
#

that is why it wants a clip as the arg

rich adder
#

this thing ^ thats signature of a method

shell sorrel
#

just have your script reference the clip you want to use so it can be passed to PlayOneShot

torpid snow
rocky canyon
#

its affectively dragging a clip into that slot for u, playing it, and then continuing doing audio source stuff

slender nymph
# torpid snow but the thing has a dang clip in the inspector???

the PlayOneShot method has nothing to do with the audio clip assigned in the inspector on the AudioSource. It is used to allow an AudioSource to play more than one clip at a time (or to more easily change which clip you want to play such as in your case)

rocky canyon
#

you can set the clip urself and then use other methods to play it.. but OneShot is just the right tool for the right job most times (imo)

rich adder
#

the one assigned in the audiosource clip section in inspector only works with Play()

torpid snow
#

i am absolutely clueless right now

rocky canyon
#

start testing stuff

torpid snow
#

good idea

rocky canyon
#

find an audioclip and go hamm 🥩

shell sorrel
#

try stuff and read docs for the things you are uisng

rich adder
#

yup best way to learn is experiment, consult manual repeat

torpid snow
#

For now play works fine

#

I’ll fig that stuff later, gotta go :/ also huge thanks once again!!!!!!

rich adder
#

Play has its flaws, for example it cancels the previous sound

#

(if you have not enough spacing between the two it stops the first one from playing)

torpid snow
#

Oh

rocky canyon
#

since it has PlayOnAwake u could for simplicities sake say.. have 3 gameobjects each Named a different Sound.. put an audiosource on each.. and then put a specific clip into each slot of the audiosources.. then u could enable a gameobject and it'll just play a sound.. and then disable it so on and so forth..

#

buuut... the shorter way to do all that.. is reference the audiosource and call OneShot on it

shell sorrel
rocky canyon
#

lol.. exactly

shell sorrel
#

since you would need to check for the sounding ending

rocky canyon
#

nah, ud disable and enable.. (once it ends it ends)

torpid snow
#

Yeah, once I get back I’m gonna try and learn one shot. It sounds simple but I just don’t know how to do it currently

rocky canyon
#

then when u ready to play it again.. u disable and enable

#

rinse and repeat.. but yea.

#

not relevant.. just use OneShot.. lol

torpid snow
#

Lmao, right.

rocky canyon
torpid snow
#

One shot allows for stuff like random pitch? Or would I need a separate stuff for that

rocky canyon
#

its realllly simple... [audiosourcereference].PlayOneShot([audioclipreference]);

torpid snow
#

I screenshotted that, have to try that.

rocky canyon
#

full script being just

public class AudioManager : MonoBehaviour
{
    public AudioSource bassButtonDropSource;
    public AudioClip bassButtonDropClip;

    public void PlayBassDrop()
    {
        bassButtonDropSource.PlayOneShot(bassButtonDropClip);
    }
}```
shell sorrel
rich adder
#

thats why sometimes having multiple audiosources for different scope is okay

torpid snow
#

This may be ambitious but could I do it off of my current speed to pitch? (Fast speed high pitch, low speed low pitch?

rocky canyon
#

suur

shell sorrel
#

would be fairly easy

rich adder
#

your imagination is your limit

rocky canyon
#

u could even remap it.. set high and low range

torpid snow
#

That seems like another can of worms for me though lmao

rocky canyon
#

it is..

rich adder
#

welcome to the rabbit hole

rocky canyon
#

another can, another feature

torpid snow
#

I miss scratch…

rich adder
#

nah code is gonna be easier

#

you'll see

shell sorrel
#

once you get used to a full programming langauge, it will feel a lot better

torpid snow
#

I got all the logic, just not the knowledge. Like a storyteller who can’t write lol

shell sorrel
#

its a skill just takes some time and practice to get the hang of things

rich adder
#

like going to foreign country , can't expect to know the native tongue right away lol

torpid snow
#

Half of coding is just persisting through the urge to quit, it feels

rocky canyon
#

i made a game in scratch after learning unity

#

it was awful experience

shell sorrel
#

its really no different then any other skill to learn you just have to give it time and practice and do it

torpid snow
#

Lmao, sounds fun

#

I made ONE game on scratch and it’s my magnum opus

#

Truly a spectacle of computers

#

Anywho thanks again for all the help, and sorry for eating y’all’s time!

#

Imma try and find out about one shot

bold iron
#

!code

eternal falconBOT
bold iron
#
    private IEnumerator motion(){
        transform.Translate(Vector2.up*Time.deltaTime);
        yield return new WaitForSeconds(2);
        transform.Translate(Vector2.down*Time.deltaTime);
        yield return new WaitForSeconds(2);

        
    }

#

ive tried to make something that would make a object go up and down. Does anyone recognize anything wrong here? As the object will start going up very fast and stop. After it would move up and down at a very inconsistant rate/

#

ive made a theory that Vector.up make it so that the object goes to the original postition similar to 0,0,0 but with a digit change on the y axes tho i have no idea why it twiches

wintry quarry
wintry quarry
#

Basically - it's doing exactly what you wrote

bold iron
wintry quarry
#

Indeed

bold iron
covert owl
#
        grid = new Grid<GridObjects>(gridWidth, gridHeight, cellSize, Vector3.zero, (Grid<GridObject>g, int x, int y) => new GridObject(g, x, y));
                                                                                                     ^(15,103)

Assets\GridMap\Scripts\Testing.cs(15,103): error CS1678: Parameter 1 is declared as type 'Grid<Testing.GridObject>' but should be 'Grid<GridObjects>'

#

this error messege aint making sence

wintry quarry
#

How many times are you starting the Coroutine?

wintry quarry
#

You put the wrong type as the first parameter in your lambda

bold iron
# wintry quarry It will pause the code for two seconds

it actually stops the code's coroutine but doesn't stop the whole code. What i did was introduce a cooldown system the same i did for my dashing skill. Now it works but im still trying to find why it codes up a lot at the start of the code.

#

the coroutine started each frame, thats why it was so inconsistent

covert owl
#

its saying it should be 'Grid<GridObjects>' when it is

eternal needle
covert owl
#

and when its not that everything breaks

#

more

wintry quarry
eternal needle
covert owl
#

no

#

✅ Get the Project files and Utilities at https://unitycodemonkey.com/video.php?v=dulosHPl82A
🌍 Get my Complete Courses! ✅ https://unitycodemonkey.com/courses
👍 Learn to make awesome games step-by-step from start to finish.
🎮 Get my Steam Games https://unitycodemonkey.com/gamebundle

✅ In this Unity Tutorial, let's make an Awesome Grid Building S...

▶ Play video
eternal needle
#

you copied the code wrong then, look closer and follow it exactly

#

im surprised code monkey used such code for whats meant to be beginner friendly tutorials. i asked about if you used AI cause using lambdas like that is not beginner friendly at all

covert owl
#

i made sure it was right, even going letter by letter

wintry quarry
#

This is pretty typical for codemonkey

#

It really doesn't teach beginners much

eternal needle
#

notice no plural on theirs

#

tbh you should just write it exactly using the same names. Even changing stuff like GridXZ to Grid makes it harder to find errors

covert owl
#

the GridXZ and Grid are the same, one is the 3D the other 2D

#

his words

regal star
#

hi guys. im trying to make this basic twin stick controller and seem to be stuck. I've got the general movement of the character down and it works pretty well. The issue I'm having is both getting the controller to detect when a gamepad is in use and getting the right stick to rotate the model. the script appears to be doing so, but nothing actually happens when i switch to a gamepad besides being able to move the character around. Any help is appreciated

https://pastebin.com/i0xuyKNv

sullen perch
#

is there a way that i can acces all the trees individualy that i spawned in with mass place?

vestal valve
cosmic dagger
vestal valve
cosmic dagger
#

oh, okay . . .

vestal valve
cosmic dagger
sullen perch
#

is there a way that i can acces all the trees individualy that i spawned in with mass place?

cosmic dagger
wintry quarry
sullen perch
#

nvm

#

realised what i wanted wont work

bold iron
#

why do people use?

#
myResults = otherGameObject.GetComponent<ComponentType>()
wintry quarry
#

As opposed to?

bold iron
wintry quarry
#

They need something from the component

#

Not the GameObject

bold iron
#

so lets say just directly writing myResults.SetActive(false);

#

oh

wintry quarry
#

Presumably they're doing something other than calling SetActive

#

Which is part of GameObject

bold iron
#

thank you, because ive seen multiple people trying to directly changing the game object with the GetComponent which gave my a error each time i do it

wintry quarry
#

Nobody does that

#

It doesn't make sense

#

And as you see, doesn't work

sullen perch
#

i wanna spawn destinations for ai in a grid around my terrain, my terrain is very big, is there a way to do this so it also sit on the terrain and not under the terrain?

wintry quarry
sullen perch
#

idk what that is, im realy new to unity

wintry quarry
#

Time to Google it

bold iron
sullen perch
regal star
torpid snow
#

@rich adder you beautiful son of a gun! Got it working perfectly, random pitch, random sfx and all. It truly puts a tear to my eye