#💻┃code-beginner

1 messages · Page 231 of 1

teal viper
#

Yes, you'll need to reference the buttons that you want to pass into the method.

#

First one is presumably a field(depend on where it is declared), the other one is a property.

viscid needle
#

Player controller Script

teal viper
#

Assuming these files are videos, you should upload them as mp4.

viscid needle
#

kk

quartz mural
quartz mural
#

how do i make it not null?

teal viper
eternal falconBOT
viscid needle
#

Hey guys! I was following the create with code begginer series by unity, I am in Unit 3, in the game the player avoids obstacles running through an endless forest. So obviously the background is supposed to be moving and the obstacle moving and the player stays still and jumps to avoid the obstacles. But in the scripts when I try to call the game Over function to stop the background and the obstacle the player movements Instead Of move left script the player stops jumping and the obstacle and the background keep on moving. pls help. Here are the scripts and the videos discord link to the above messages
#💻┃code-beginner message (expected Version)

teal viper
viscid needle
#

how do I share it better

teal viper
viscid needle
teal viper
viscid needle
#

with the problem

frigid flume
#

i changed things because nothing worked

teal viper
frigid flume
#

yes

#

i have the script on all the buttons

teal viper
frigid flume
#

each button calls a different function

teal viper
frigid flume
#

but i don't want that at the end

short agate
#

Good morning, I'm finishing my first game. But I'm stuck on something that should be simple but I don't know how to do it. my boss summons these demons. However, if you die and try to press restart the game crashes, from what I think, it's because the demons are trying to follow the player, but the player is dead and has nothing to follow. How do I not have any more summons when the player dies? I will send the link to the codes below. demon controle; https://paste.ofcode.org/Wf8QGE6PrVX5AFQNX9ufNP player; https://paste.ofcode.org/RDJn7EBygswTGacKTiaxgQ boss; https://paste.ofcode.org/r5fYms2KqPpKb3KdNSqpfz

frigid flume
covert matrix
#

i currently have functions that saves a score to an inputted id

    {
        string studentID = PlayerPrefs.GetString("studentID", "");
        
        // Save total score
        string totalScoreKey = $"TotalScore_{studentID}";
        PlayerPrefs.SetInt(totalScoreKey, playerScore);

        PlayerPrefs.Save();

and displays it in a different scene when the id searched for matches a saved inputted id

string totalScoreKey = $"TotalScore_{studentID}";
int totalScore = PlayerPrefs.GetInt(totalScoreKey, 0);```
it currently works but if the same id is inputted multiple times, the data gets overwrriten, but i want to display all attempts scores, how do i account for that?
quartz mural
viscid needle
ruby python
#

Having a bit of a moment, but how can I get the current rotation speed of an object? I'm using transform.Rotate to rotate the object.

teal viper
# frigid flume i don't understand at all sorry

Something like this:

Object with script and button 1
Object with script and button 2
Object with script and button 3
etc...

Each object would have a script that references the corresponding button. And in the script:

[SerializeField] private Button myButton;
void MethodToCallFromButton()
{
  DoSomethingWithThisButton(myButton, someBool);
}

Makes sense?

frigid flume
#

a bit...

upbeat stream
frigid flume
teal viper
teal viper
vale cradle
#

i have a really dumb question but i want to know how to select the frames from animation like this?

frigid flume
viscid needle
covert matrix
teal viper
teal viper
frigid flume
#

is what call a method ModificationCase() for example ?

upbeat stream
covert matrix
#

thank you

hexed terrace
upbeat stream
# covert matrix thank you

np. just read up on json serialize/deserialize, then you can save larger data sets in playerprefs easily. might have to clear your prefs if you change the structure of the class though

vale cradle
hexed terrace
teal viper
vale cradle
#

i mean if you know then tell me

frigid flume
#

is this a method

#

i call that a function but maybe it's the same thing

teal viper
frigid flume
#

method and function

upbeat stream
#

he's asking if Methods and Functions are the same thing

frigid flume
#

or is method a line of code like Debug.LOg

teal viper
teal viper
#

A method is the same thing as a function.

frigid flume
#

ok thanks x)

cosmic dagger
frigid flume
#

so i create a different method for each button right ?

teal viper
#

Please use puncutation, because it's not even clear wether you're asking a question

cosmic dagger
#

@frigid flume the be politically correct: the difference is, a method is a function associated with a type (in this case, a class) . . .

frigid flume
#

ok thanks

#

i am understanding so slowly mad

teal viper
#
button1 on object1 => Script on object1 Method() => Method(parameters referenced in this script)

button2 on object2 => Script on object2 Method() => Method(parameters referenced in this script)

button3 on object3 => Script on object3 Method() => Method(parameters referenced in this script)

Makes sense?

frigid flume
#

i'll try and show you

frigid flume
tall vortex
#

whats the best unity editor for begginer trying to make a 3d fps lowpoly game?

rare basin
#

any

tall vortex
tall vortex
frigid flume
frigid flume
bold bone
#

Performance question

I need to use collision.gameObject.transform.position several times in my code

Would it be more efficient, creating a Vector3 variable inside OnCollisionEnter, to store collision.gameObject.transform.position
And then simply referencing it

teal viper
tall vortex
rare basin
#

just read it

#

and see what you need

#

if you want android support

#

then use it aswel

#

what's hard about it?

tall vortex
frigid flume
teal viper
#

You should probably serialize them as an array of bools. You know arrays, right?

frigid flume
#

yes but never used

#

for now it's good :)

cosmic dagger
teal viper
bold bone
bold bone
#

sorry for wrong terminology

teal viper
#

Class variable(field) vs local variable

cosmic dagger
#

whichever method you access transform.position multiple times, store a local variable of the position, then update it at the end of the method . . .

#

if you use the collided transform in multiple methods, then yes, i would create a class variable for the collided GameObject's transform . . .

#

you can assign it in OnCollisionEnter . . .

bold bone
# teal viper Class variable(field) vs local variable

yeah thats what i mean, would it make a difference if the variable is global or local? (i will only use it inside OnCollisionEnter)
since OnCollisionMethod will be called pretty often i would need to be often creating new Vector 3 variables, which may cause more garbage collection
correct me if im wrong

frigid flume
bold bone
#

or would i still need to be creating new Vector3 anyways, since every collision will have a different position

teal viper
teal viper
frigid flume
frigid flume
cosmic dagger
teal viper
hollow zenith
#
Sprite position:
x: -5.68
y: 2.47

Parent position:
x: 1.78
y: -1.09

when I get sprite game object position gameobject.transform.position I get:

x: 3.54
y: 0.88

Any ideas? I am trying to convert sprite position into world position(so I can position some UI elements)

#

Those numbers dont seem to match, localPosition gives better results but its still off.

wintry quarry
hollow zenith
#

Sprite has scale of 5 tho if that matters?

wintry quarry
#

what kind of objects are these?

hollow zenith
#

From regular objects, not UI

wintry quarry
#

ok and these numbers came from?

#

Show the code

#

and show the scene and what you are confused about

wintry quarry
#

what object is that?

#

No context here

hollow zenith
#

I want to get this number into UI so I can show UI on top of the character sprite.

polar acorn
#

The inspector shows local position, relative to it's parent

wintry quarry
#

.position is world space position

hollow zenith
#

Yes, I tried to calculate normal position using parent offset and the math doesnt add up

wintry quarry
hollow zenith
#

localposition - parent I guess

wintry quarry
#

if you want the world space position of a GameObject that's just Transform.position

frigid flume
hollow zenith
#

oh

polar acorn
hollow zenith
#

So there is no need to do

        Camera.main.WorldToScreenPoint(startPos);
#

If I get .postion

frigid flume
#

accross different scenes

teal viper
#

It would be tricky if you had to hardcode every bool(like you do now)

polar acorn
hollow zenith
#
Vector3 targetPosition = CharacterAnimator.gameObject.transform.position;
Camera.main.WorldToScreenPoint(targetPosition); // When I use this Vector to create UI it appears at an offset
#

ok found the issue

#

I was using localPosition on UI

teal viper
eternal falconBOT
#

:teacher: Unity Learn ↗

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

hollow zenith
#
        transform.position = Camera.main.WorldToScreenPoint(startPos);

This works so far, I knew something was up since it worked earlier, but I was messing up with the code and things didnt work anymore 😄

frigid flume
teal viper
#

You can do whatever you like if you code it

#

Setting manually in the inspector is an option to, although it becomes unfeasible very fast.

icy junco
#

anyone who canhelp me with some photon pun bug?

dapper egret
icy junco
#

wdym?

hollow zenith
#
        transform.position = Camera.main.WorldToScreenPoint(startPos);
        Vector3 currentPos = transform.position;

        float randomX = startPos.x + Random.Range(-0.2f, 0.2f);
        transform.position = new Vector3(currentPos.x + randomX, currentPos.y, currentPos.z);

Anyone would change anything in this code? Am I doing it right?
I cant seem to find a better way to change x or y of a transform without having to do new Vector or writing a long line of code.

dapper egret
#

As far as i am aware you pay quite a bit for ccu for the dedi servers

icy junco
#

yeah i am just uding free version

#

what would be a better option ?

dapper egret
#

You can always try unitys networking or even go with fishnet if you want

icy junco
#

allright i will look into that

#

i also have question for you because you seem to know a bit around server side, is it diffucult to setup your own dedicted server for a game using like an old pc or anything like that ?

dapper egret
#

Not at all,you can always do peer 2 peer througj a relay or go through the pure dedi server one,plently of free online options available

teal viper
icy junco
teal viper
#

To a degree. Not something for production where you expect hundreds of people to connect to the server.

#

You'd also need a way to share the ip address of the server with the users if it's a dynamic ip.

icy junco
#

yeah but like a small server for like my friends?

frigid flume
#

how do i define which index of the array has to be used when button's clicked

teal viper
icy junco
teal viper
frigid flume
teal viper
frigid flume
#

for the moments it's useless

frigid flume
#

what i tried to do is to assign an int to each emptyobject so it's used to pick the bool from the array

teal viper
frigid flume
#

works a bit

#

almost perfectly

#

thanks a lot for your help and sorry for the dumbbeing

worthy merlin
#
   {
       SceneManager.LoadScene(SceneManager.GetActiveScene().name);
       highScore = PlayerPrefs.GetInt("highScore");
       Debug.Log(highScore);
       if (highScore < 0)
       {
           Debug.Log("High Score is below 0!");
           highScoreText.text = "No Scores Currently";
       }
       if (highScore > 0)
       {
           Debug.Log("High Score is above 0!");
           highScoreText.text = "High Score: " + highScore.ToString();
       }
   }

All of this code is working, but for some reason the highScoreText.text is resetting to the default value of No Scores Currently despite no other code interacting with it in the program. Any idea why its doing this? Also highScoreText is a TextMeshPro if that helps.

keen dew
#

highScoreText in this code refers to the field in the old instance of the scene, not the new scene

spiral narwhal
#

That's bound to lead to bugs

worthy merlin
stoic ridge
keen dew
#

Put the code that prints the high score into a Start method of some object in the scene

worthy merlin
#

Gotcha

spiral narwhal
worthy merlin
#

Lol

spiral narwhal
#

🤷‍♂️

stoic ridge
#

sorry my grammar is weak if any problem

spiral narwhal
#

Because right now it says public Private MethodScripts privateMethodScripts struct Glyph...

#

Do you want it to be public or private?

#

Btw I recommend setting up your IDE to show you the compilation errors

#

And some good starter C# tutorials are pinned

keen dew
#

The code is just nonsense

slender cargo
#

How would you recommend that I save a pre-fabs position so when I quit and reload my game, they are in the same position with the same information.

keen dew
#

Are you trying to modify TextMeshPro source code?

spiral narwhal
worthy merlin
spiral narwhal
#

Using game saves

spiral narwhal
# stoic ridge

Yes I know. Just like I said, take a look at the basics of C# first

#

That member header is nonsense

summer stump
# stoic ridge

There is a LOT wrong with that code
What is your goal with that code?

stoic ridge
strong wren
summer stump
# stoic ridge

You have posted that already.
Use your words to describe what the code is FOR. Right now, as they said, it is nonesense. It is completely wrong in many ways. It is impossible to know even what you are ATTEMPTING to do, so you need to explain before we can help.
Sorry

#

Oh, I see you DID make one small change. It is not enough to fix it, bit it is a step in the right direction

slender cargo
burnt vapor
# stoic ridge

Configure your !ide and then come back with your question

eternal falconBOT
carmine elm
#

can somne help me the error is NullReferenceException: Object reference not set to an instance of an object and is on the line with GetComponent

burnt vapor
eternal falconBOT
spiral narwhal
strong wren
slender cargo
spiral narwhal
burnt vapor
# slender cargo I'll take a look

As soon as it stops working and returns no data on serialization consider using Newtonsoft instead. JsonUtility is very old and has a ton of limitations which prevents it from working correctly.

spiral narwhal
#

Basically it means somewhere you are using the access operator ., its value is null. Since it doesn't have a value, you can't access anything

stoic ridge
#

I change some code

spiral narwhal
#

@burnt vapor ❌ ? :D

burnt vapor
eternal falconBOT
burnt vapor
summer stump
slender cargo
#

So found this online... Looks like it will work well. What script type would I want this to be on? And why is "File" invalid

burnt vapor
#

Helping them mostly just ends them up with them solving the question and still using a misconfigured editor

spiral narwhal
#

It's probably not imported

burnt vapor
slender cargo
#

So I'd Just want to call Load Player on start, and save player on application quit?

polar acorn
slender cargo
#

is that the general basics?

spiral narwhal
stoic ridge
burnt vapor
summer stump
stoic ridge
#

ok

slender cargo
spiral narwhal
slender cargo
#

Would you create some sort of loop that gets all the pre-fabs, and sets them all as seperate data sets, then when loading I can just re-instantiate them

#

I could get all the pre-fabs, add them to an array, then go through the length of the array saving them?

craggy laurel
#

I have a script that basically rotates cards, moving the leftmost to the right and all others one position ot the left. I get huge GC Collection Spikes when I call SortCards(). Can someone tell me why?

#

I was thinking it might be related to a big amount of new Colors being generated in MakeCardAppear / Disappear?

olive heron
#

starting too many coroutines, at first glance

frigid flume
craggy laurel
polar acorn
rich adder
slender cargo
#

Would this be a good way of saving pre-fabs, if so, how should I go abouts doing?

polar acorn
rich adder
#

ahh yes myb discord funny

swift crag
polar acorn
swift crag
#

What are you trying to accomplish here?

keen dew
slender cargo
swift crag
polar acorn
swift crag
#

they're assets in your project

keen dew
slender cargo
#

Right so, My breeding script instantiates in a new creature which holds a data set. When I reload the scene, I want that instantiated pre-fab to re-instantiate containing the same info it had

swift crag
#

Are you trying to remember which items your player has?

keen dew
#

them calling the instantiated objects "prefabs" is the confusing part

polar acorn
rich adder
carmine elm
#

@burnt vapor can you help me now i done every thing

swift crag
#

You will need to serialize the data that you need to remember.

slender cargo
#

This is the info on the pre fab

swift crag
#

It could look like this

#
[System.Serializiable]
public class EntityData {
  public int level;
  public string name;
}
craggy laurel
slender cargo
swift crag
#

You'd store the data you want to remember into an instance of EntityData and serialize it with JsonUtility, then write that data to a file.

#

you could also just store EntityData somewhere and use it later

slender cargo
#

ohh

swift crag
#

You'd then write code that reads EntityData to configure your entity

#

That's the gist of serialization and deserialization

#

Turn your runtime objects into data

languid spire
#

@small chasm Do NOT send unsolicited DM's to people in this server

swift crag
#

Then turn your data back into runtime objects

slender cargo
#

so each pre-fab can call public EntityData data; then all write their data to that?

swift crag
#

Each instance in your scene would be serialized

#
public EntityData Save() {
  EntityData data = new();
  data.level = myLevel;
  data.name = myName;
  return data;
}

public void Load(EntityData data) {
  myLevel = data.level;
  myName = data.name;
}
#

It could look like this.

#

Or maybe more like

#
public void Save(EntityData data) {
  data.level = myLevel;
  data.name = myName;
}

public void Load(EntityData data) {
  myLevel = data.level;
  myName = data.name;
}
#

I do this in my game. Someone else is responsible for creating the EntityData when saving

polar acorn
rich adder
#

GetComponent only thing strikes me weird as well

carmine elm
#

can somone help me

polar acorn
rich adder
slender cargo
spiral folio
#

can someone good with unity save me from having a mental breakdown

swift crag
opal portal
#

Hello there, I'm planning to create custom events, should I use my own event system, or Unity has something for that?

spiral folio
rich adder
swift crag
swift crag
#

GC.Collect is going to have no garbage

craggy laurel
swift crag
#

If you don't need to save data between game sessions, you don't need to do this

#

You can just store your save data anywhere (maybe in your "game controller" class)

opal portal
spiral folio
#

i cant get the enemy to damage the player on collision, on debug there deffo colliding and ive also set up p as the key to test health loss... both work just not together

opal portal
#

love ya

languid spire
eternal falconBOT
spiral folio
languid spire
#

no, read the bot message

pallid nymph
craggy laurel
swift crag
#

so you'll need to save an ID that you can then use to figure out what to spawn

#

You could give each prefab its own ID and then make a list of all of your prefabs

#
[System.Serializiable]
public class EntityData {
  public string identifier;
  public Vector3 position;
  public int level;
  public string name;
}
#

your save data might look like this now

fringe plover
#

Hi, is there any method that allows you to read all files in folder? (Im using Json files to say stuff)

polar acorn
fringe plover
#

Okay thanks

slender cargo
slender cargo
amber nimbus
#

!code

eternal falconBOT
polar acorn
slender cargo
# slender cargo

This is what I've sourced from the internet, But I don't know how im creating the sets of data from the prefabs

polar acorn
slender cargo
#

This is what I've got from @swift crag But not sure how I call this?

polar acorn
#

you'd write the json to a file to save it. You'd read the json from the file to load it

#

@amber nimbus I think your first attempt at code was formatted properly but I didn't get a good look at it

slender cargo
amber nimbus
#
Vector3 lookDir = target.position - transform.position;
lookDir = Vector3.ProjectOnPlane(lookDir, transform.right);
Quaternion rot = Quaternion.LookRotation(lookDir, transform.right);
transform.rotation = Quaternion.RotateTowards(transform.rotation, rot, gunSpeed * Time.deltaTime);

Hello, working on a game and I have this code, what I am trying to achieve is to use the RotateTowards() method, but rotate the object only around the X axis, what I did here does not work at all I was just wondering if anyone knows a way to do this :D

polar acorn
amber nimbus
#

Correct

umbral gazelle
#

Does anyone know why I’m getting this error? And sorry it’s a picture and not a screenshot I’m working on a school computer

languid spire
umbral gazelle
#

This work is in another script I have for my bullets and enemy’s so I’m wondering why it’s not working here. My enemy and bullets die on contact but I want my player to lose health

languid spire
#

big doubt, that code will not even compile

umbral gazelle
#

But it does tho

languid spire
#

also yout !IDE is not configured, do that before asking for more help

eternal falconBOT
polar acorn
# amber nimbus Correct

Still trying to internalize this a bit how this would look. So, if the targit is above and behind the object, you want it to angle up, but not rotate towards the object, right?

Like, if this object is at 0,0,0 and the target is at 0,5,-5 you'd want this object angled up 45 degrees continuing to look forward?

umbral gazelle
#

Because everything was working until I added what I just showed

polar acorn
#

why do you have a switch statement with one condition

umbral gazelle
amber nimbus
keen dew
polar acorn
umbral gazelle
amber nimbus
#

Yes, but the gun object needs to only rotate around X

umbral gazelle
keen dew
#

And you don't see any difference when comparing to the one that doesn't work?

umbral gazelle
polar acorn
amber nimbus
#

Exactly

polar acorn
#

also don't use switch statements with one case, use an if

umbral gazelle
# keen dew What do you think `break` does?

Can you guys actually try and help me instead of criticizing what I’m doing. I get you guys do this for a hobby/job but someone’s who’s new has a hard time learning this stuff and when people just basically call you stupid it makes coding not fun

keen dew
#

We are trying to help you

#

It was a serious question. If removing break makes the code not work, a) what do you think break does and b) why did you remove it and still expect it to work?

rich adder
umbral gazelle
#

Well I get that break breaks that game object but I’m trying to get my take damage to work when the player collided what code would I put?

rich adder
gaunt ice
#

break is a keyword

shadow zephyr
#

break will exit whatever loop or function you’re in

polar acorn
# amber nimbus Exactly

Okay hang on I'm trying to think this out, I've gotten halfway through describing it like five different ways before I realize it won't work and deleting it

shadow zephyr
#

it’ll just not execute the rest

polar acorn
umbral gazelle
#

Oh so I was getting it confused with the destroy?

amber nimbus
umbral gazelle
polar acorn
umbral gazelle
polar acorn
umbral gazelle
#

It says that it need a bracket there but if I put one there’s an uneven amount and everything in incorrectly bracketed

polar acorn
eternal falconBOT
polar acorn
#

Why is there a case with an if statement

#

why is the case empty

#

why is any of this

timber tide
#

neat language what is it

polar acorn
#

Can't just get the LookRotation vector and zero out Y and Z, because there's no guarantee the euler angles of it will be in that exact form...

summer stump
modest dust
#

I think that's the smallest issue here

summer stump
modest dust
#

If he doesn't understand what he's doing

polar acorn
# umbral gazelle I meant destroy I was getting destroy and break confused

Okay, I think I have an idea.

Get the vector from this object to the target, target.position - transform.position.
Then, set that vector's X to zero, and the Z to absolute value of Z (this will avoid the turret looking behind itself)
Then you should be able to use LookRotation with that vector, and set this objects .rotation to that Quaternion

Misping @umbral gazelle, sorry this was for someone else

summer stump
#

@amber nimbus ^ this was meant for you I think

polar acorn
#

It was I'm sorry

carmine elm
#

when ever i underline somtething to delete a line or anything the mode from insert gose in , inlite proposal i think is called. How can i disable it?

wintry quarry
lost anvil
#

im still working on a player interaction system but have run into an issue where when i want to drop the item, i have to look at the untagged ground. and even then it gives me an object reference error and doesnt drop it

            // PICKUPABLE INTERFACE DECLARATION
            if (Input.GetKeyDown(KeyCode.E) && interactObj.CompareTag("Pickupable") && isHolding == false)
            {
                Debug.Log("pickup");
                isHolding = true;
                interactObj.GetComponent<IPickupable>().Pickup();
            }
            else if (Input.GetKeyDown(KeyCode.F) && isHolding == true)
            {
                Debug.Log("drop");
                isHolding = false;
                interactObj.GetComponent<IPickupable>().Drop();
            }
polar acorn
carmine elm
#

i have to press it like evry 3 secons

polar acorn
#

Then maybe your keyboard is faulty

carmine elm
#

ok thanks

polar acorn
#

assuming interactObj is something in a collision or raycast

lost anvil
#

yeah interactObj is set as a gameobject the raycast touches

amber nimbus
#

I have no idea have you came up with that

lost anvil
hidden sleet
#

Currently trudging through some code reorginsation to implement something new and I've basically had to go and redo most things in it, it's structure is really not ideal. Are there any places to get some kind of code review to see how I could restructure it? It's not looking good and could be so much better, but I'm not too confident on what could be changed

timber tide
#

here

hidden sleet
#

I feel like chucking it all in here would be a bit much

night mural
hidden sleet
#

Unless I sort of abstract it into ideas rather than every single line

cosmic quail
hidden sleet
#

I’ll see what I can do

night mural
polar acorn
lost anvil
meager steeple
#

which has the correct syntax highlighting? and why are they slightly different?

polar acorn
polar acorn
lost anvil
meager steeple
polar acorn
meager steeple
eternal falconBOT
fringe plover
#

What the-

hidden sleet
#

Was trying to write it out but I can't find a feasible way to explain it. The way I've done it is rather convoluted and has so many connected parts. Essentially it's an inventory system with three types, but each type has methods that themselves take different types and do different things, and item containers that are also different types. Each of them has a container, and methods to add / remove items, but I've got them all separate, and I don't know what I could do to have them all a bit easier to follow.

I've tried having a superclass they all inherit from, but then if I call .AddItem or whatever on that super, it won't work since the methods are different for each and the types are different for each

wintry quarry
polar acorn
#

C# won't know that's nonsense until it tries to actually do it

wintry quarry
#

What part doesn't work

#

what are you trying to do that won't work?

fringe plover
wintry quarry
#

did not send code

rich adder
#

shouldn't that at least give you warning being non-component in console

hidden sleet
#

That's the thing, if I go into it i'll be spewing pages upon pages. I'm trying to find an easier way to describe it but I can't really pinpoint it yet. It all stemmed from me wanting to change something but it's just messy at the moment

hidden sleet
#

just ignore me for now, I'll try and get something more concrete

wintry quarry
# hidden sleet That's the thing, if I go into it i'll be spewing pages upon pages. I'm trying t...

Well the details are important. Right now it's pretty vague. At a high level let's say you have three different items. Maybe one is a potion, one is a sword you can equip, one teleports you home. If you are doing an inheritance pattern there should just be an abstract function called Use on the parent class, and each subclass would implement Use in its own way. For example the sword would equip itself to you, the potion would restore health, and the teleporter would teleport you.

#

that being said inheritance is not always the best architecture

#

composition is often better

hidden sleet
#

how does that differ?

wintry quarry
#

so an item could instead all just have something like List<Effect> - where Effect is now an interface for example or abstract class, and every item you just loop over all its Effects and apply them

#

Or Effect is a delegate type

#

pointing to different functions

crimson ibex
#

Hello, I have been struggling for a week now, to which seems like a simple thing.
In my 3d game, a character will move on a 2d plane and interact with 5-6 unmoveable gameobejcts.
I can not figure out if navmesh agents is best way to move the characater, or handle movements myself .I have tried both and face many problems in both approach . I do not need physics.
Please guide, which is theoritically better .

wintry quarry
#

there could also be other things like giving them a List<UsageConditions> which you loop over to determine if they're currently usable

wintry quarry
#

It depends on what you are trying to achieve

#

and "handle movements myself" could mean almost anything

fringe plover
crimson ibex
rich adder
#

sounds like navmesh is perfect then

crimson ibex
night mural
#

you can always use the nav mesh to do pathing and then move along those paths using your own movement in wahtever way you want

rich adder
wintry quarry
#

also is it a grid?

crimson ibex
#

not a grid

wintry quarry
#

NavMesh is probably the simplest way to start

night mural
#

sounds like you should navmesh it up

crimson ibex
rich adder
rocky canyon
#

all ur obstacles should be carving empty spacing in the navmesh

#

he'll automatically find a path around them

hidden sleet
#

If for example I had a StructuresInventory that had AddStructure, and an itemInventory that had AddItem, both inheriting from Inventory, if I were to pass in just Inventory elsewhere, would that not be able to perform either methods from those other two inventories? only the methods from Inventory itself?

polar ravine
#

How do I can use the Collision2D variable of OnCollisionExit2D in another method?

rich adder
#

store it in a Collider var or something
or pass it through method params if you need to call it right away

cosmic quail
crimson ibex
hidden sleet
crimson ibex
#

is it trouble-some to use colliders+rigidbody with navmesh ai ? Can they mix

night mural
crimson ibex
rich adder
#

not sure why you need rigidbody for that

#

the navmesh is moving the transform and it conflicts with rigidbody movement,
You can put a locked /kinematic rigidbody for example to push other rigibodies though

buoyant rune
#

!code

eternal falconBOT
crimson ibex
crimson ibex
rich adder
#

Raycast, Overlap, Casts etc.

buoyant rune
hidden sleet
crimson ibex
night mural
rich adder
#

you can only set it from inside this class
also sometimes raycast maybe too thin, there are other methods like boxcast, spherecast etc

rich adder
night mural
crimson ibex
#

Thank you everyone, @rich adder , I will attempt as suggested .

buoyant rune
hidden sleet
night mural
rich adder
night mural
#

sounds like maybe that's not an inventory though, since inventories tend to be limited in space

#

maybe you're doing something more specific and complex but you'd need to explain that

cosmic quail
rich adder
#

also this should be
_isMoving = inputMovement != Vector2.zero
not ==

night mural
buoyant rune
rich adder
#

nothing to do if game is 3D or not

hidden sleet
#

If I can find a way to simplify it then I'd love to. But since inputs into the game come from photos taken by the user, which then acts as an item, I don't know how that could incorporate an id system when there isn't any knowledge of what that item could be beforehand

rich adder
#

Unity uses both interchangeably

cosmic quail
buoyant rune
cosmic quail
hidden sleet
#

Well I was just going by what Prakkus mentioned. But my understanding is just that an inventory could hold just a number which then refers to an item elsewhere

cosmic quail
night mural
naive lion
#

Hey guys
Using timescale to pause game but the camera still rotates during pause
Not through input, but through momentum, so if I pause before I do a mouse swing, it will still rotate
I am using Cinemachine, anyone got any tips as to what I can look for to solve this

hidden sleet
#

In that case I'm probably the one who isn't following properly

cosmic quail
#

by using T

#

aka generics

hidden sleet
#

Haven't used them all to much. Some people have recommended me not to but I'm not 100% sure on their best use cases and implementations

#

I'm definitely going to try and draw up some diagrams later

rich adder
#

timescale only affects things that depend on it

cosmic quail
#

and any things specific to structures or items you handle in their own class

naive lion
#

fixed

hidden sleet
#

Can you have it so that you can perform a specific set of tasks depending on the type of the input?

dusky dirge
#

so i have an issue where, when my character runs in a straight line they randomly stop, kinda budge around on the y position, despite the ground being entirely flat. im using a box collider with unity3d (my 2.5D game) and im curious how i can stop this?

summer stump
dusky dirge
wintry quarry
dusky dirge
wintry quarry
cosmic quail
dusky dirge
wintry quarry
#

kinda defeats the point i think

#

why not just use virtual methods

wintry quarry
dusky dirge
wintry quarry
#

Is there a reason you need 3D physics?

cosmic quail
wintry quarry
#

You could use 2d physics

dusky dirge
#

ouhh uhhh

#

idk

#

i just like it this way

eternal needle
rich adder
#

are you using character controller maybe play around with skin width @dusky dirge

wintry quarry
#

3D physics doesn't have as good of a solution for this problem

#

you might have to use a mesh collider

#

and potentially generate the mesh dynamically

cosmic quail
#

yeah i would definitely use an interface here. i didnt say it because i was unsure if you could use these here

#

interface called IInventoryItem and put it on both your Structure and Item classes. @hidden sleet thats probably the best code you will have if you do it this way

#

then you need zero if's as well to check their type. cause you just call the interface's methods

pallid nymph
#

(generally for items I think composition > inheritance... but I don't know much about the discussion at hand 😄 )

dusky dirge
#

it works now, thanks for yalls help

cosmic quail
hidden sleet
cosmic quail
#

inheritance is abstract class and composition is interface? or what do you mean

pallid nymph
#

inheritance is a hierarchy of classes

#

problem is that at some point you need something to be both a StackableItem and a SomethingEleseableItem (Weapon or something 🤷‍♂️ )

rocky canyon
#

why not bolf?

pallid nymph
#

composition is... you have a single Item class, and it has different components that handle different aspects... you add Stackable component and that handles the stacking aspect, you can put it on an item that has the Weapon component, Damage component, Whatever component

eternal needle
rocky canyon
#

public class SampleScript : MonoBehaviour, IStackable, ISomethingElseable

wintry quarry
#

Unity's GameObject/Component architecture is a composition architecture.

You don't have subclasses of GameObject

#

you just attach different components to make it do stuff

pallid nymph
# rocky canyon why not bolf?

it does tend to be both, but usually it's a shallow hierarchy like interface + a few implementations right underneath it on one level, and those are then composed

rocky canyon
#

i tend to use composition

#

altho... my inspector does get cluttered

#

ngl

pallid nymph
#

yeah, I made a component that searches in the fields in all components on the current GO 😄

rocky canyon
#

there needs to be more resources on the aspect of designing a fleshed out gameobject

#

i feel i did 100 uturns / circles when i first started learning to combine scripts

#

still do.

minor saddle
#

I'm pretty new to Unity, I'm hiding buttons once they're clicked, is there a more efficient way to do this? I got so many buttons, I'm getting confused.

night mural
#

it's because the unity architecture is silly and untenable beyond little prototypes and setting up an alternative is a lot of work

#

or a lot of work to make tenable

rocky canyon
rocky canyon
#

whats silly about it? just wondering

minor saddle
rocky canyon
#

to keep urself more organized

minor saddle
#

Yeah I should really do that

pallid nymph
night mural
#

we need rules, people

#

we live in a society

rocky canyon
#

then u put it in reverse 😄

pallid nymph
#

then again, there's ECS, which many people will tell you "it's the future and the one true way of doing game dev", and there all data is public

rocky canyon
#

🔥 BURN

night mural
# rocky canyon ahh i see

Bobby explains a lot of the problems well here (timestamped) https://youtu.be/jjEsB611kxs?t=562

A long brain dump about entity/object models in game engines today...

Follow-up on additional questions: https://youtu.be/fuiNOWEUnJ8

Prototype implementation: https://github.com/BobbyAnguelov/KRG

00:00:00 - Stream Start
00:00:07 - Intro
00:04:44 - What is an Object/Entity Model
00:09:24 - Game Object Component Model (OCM)
00:16:54 - OCM: Ref...

▶ Play video
rocky canyon
#

is that ECS related? or general unity

#

or General Game Engines

night mural
#

the whole video is an overview of the various ways in which engines tend to model entities (including ecs) and some of the pros/cons of each one

rocky canyon
#

ahh okay. i'll give it a bookmark 👍

night mural
#

first he talks about the unity/unreal/etc model, then ecs, then his own opinions on what a good hybrid looks like (but the part i linked is about the unity style)

rocky canyon
#

i feel like u need a CS degree to understand how to use ECS

pallid nymph
#

one might say ECS is more organized and simpler

hidden sleet
#

How can I find where this event that I've invoked actually does something? OnItemRemoved?.Invoke();

pallid nymph
#

(Disclaimer: I've not done much ECS though)

wintry quarry
rocky canyon
#

use find in ur IDE on OnItemRemoved

#

look for the subscription ^

#

usually in awake/ start/ onenable

hidden sleet
#

I tried find references but couldn't spot anything

rocky canyon
#

just use Find

hidden sleet
#

actually let me double check that it's actually being used. Will remove it and see

wintry quarry
#

if nothing is subscribing then it's not doing anything

summer stump
rocky canyon
#
   void Awake()
    {
        // Subscribe a method to the event
        OnItemRemoved += HandleItemRemoved;  // here is a subscription.. now u know HandItemRemoved() is one of those methods
pallid nymph
summer stump
night mural
#

you could totally do 'in scene' ecs where your gameobjects are entities and your components are components and you just structure things like an ecs but i've not really tried that, donno if there's some gotchas

meager steeple
#

well i just accidentally deleted visual studio code

#

fun times

night mural
#

you probably wouldn't get the cache benefits but i'm not sure that matters much and you can learn the pattern

sage mirage
#

Hello, guys! I have a question. I heard about not using public access modifier very often and instead of public modifier to use encapsulation and get access to some fields. How can I do that, for example if I want to see my audio sources or my audio clips in my inspector which modifier to use if not public?

polar acorn
summer stump
buoyant knot
summer stump
#

Or do VS ☝️

summer stump
meager steeple
buoyant knot
#

subbing in Awake makes unsubbing a bit more difficult, since unsubbing in OnDestroy can be problematic as multiple different things might be destroyed or being destroyed

meager steeple
#

so im just gonna download from unity or whatever it is

sage mirage
summer stump
#

[field: SerializeField]
AudioSource source {get; private set;}

buoyant knot
#

public setters or public fields is bad juju, since you make it possible for random classes to fuck with your variables in ways you don’t have complete control over within that class that holds it

#

there is a time and place for them, but it is more like driving without a seatbelt

#

i almost exclusively allow external modification to fields via a few controlled public methods

sage mirage
#

Yes but if I have to make a lot of fields public, I have to make for every that field a property?

buoyant knot
#

you never have to make a lot of a fields public

#

you might need to make some fields public, rarely

#

the majority of my fields are defined as auto properties

low path
#

i think public setters can be ok since what they do is controlled by code. public variables accessible from outside a class are pretty hard to justy though

buoyant knot
#

private int x;
[SerializeField] private int y;
[field: SerializeField] public int z {get; private set;}

#

these are the bread and butter patterns

summer stump
low path
#

yeah i mean public set, public get essentially just gives you a public variable

#

but public setters that are defined are commonly used

pallid nymph
#

my main rule is that stuff should be set in as few places as possible... unless something is a generic stand-alone parameter 🤔

buoyant knot
pallid nymph
low path
#

yeah that's exactl;y what a setter is

buoyant knot
#

a public setter has to account for basically ANY sort of setting operation that could happen

summer stump
buoyant knot
#

specific methods only need to worry about one thing

meager steeple
#

i downloaded this thing but its still saying its not there, is there some specific folder i need to put it in?

rocky canyon
#

you tried googling the error?

meager steeple
#

or what is the problem

rocky canyon
#

ive never seen the error tbh

low path
#

you can limit it however you want

buoyant knot
#

once you expose the setter, the setter is now responsible for maintaining order within the class, with respect to changing any internals

low path
#

that's not true, everything inside the class can explicitly refer to the backing field

#

you can also have properties that aren't explicitly tied to individual backing fields

buoyant knot
#

if mario’s number of lives has a public setter, then that setter better know what to do with a negative number of lives, zero lives, it better invoke SFX, it better tell the UI

#

but now you can’t separate it easily

hidden sleet
#

So regarding this issue I was having earlier, I've got a better example here. I've got an cs public void UpdateDisplay(RawItemInventory inventory) { method, which will update the elements of a ui to match the inventory contents, but then another one cs public void UpdateDisplay(NewProcessedItemInventory inventory) { for a different inventory type. But since they have different inventory types and slot types, I didn't know how to streamline this cs protected NewProcessedItemInventory ProcInv; public Dictionary<NewDatabaseInvItemSlot, GameObject> invSlotToUiObject = new Dictionary<NewDatabaseInvItemSlot, GameObject>(); , cs protected RawItemInventory Rawinv; public Dictionary<GameObject, NewInventoryItemSlot> UiObjectToInvSlot = new Dictionary<GameObject, NewInventoryItemSlot>(); public Dictionary<NewInventoryItemSlot, GameObject> invSlotToUiObject = new Dictionary<NewInventoryItemSlot, GameObject>();

low path
#

but you already have methods for that?

buoyant knot
#

then why do you need a public setter

low path
#

in the end, a property setter is just syntactic sugar for a method

buoyant knot
#

you no longer have a simple way to just change the number, vs change the number and do all the ancillary stuff

hidden sleet
rocky canyon
#
public int MyValue { get => _myValue; set { /* sexy */ } }```
night mural
# buoyant knot then why do you need a public setter

is your point basically 'if you are doing something complicated when changing a value, you should probably give that operation a name and make it a method, rather than having a complicated setter which doesn't explain its intent'? cause i think i agree with you there

buoyant knot
#

a lot of my public setters with advanced logic turned into problems, separating responsibilities between specialized methods and calling the public setter

meager steeple
#

right i opened visual studio code once, i closed it and opened again and the syntaxs were different

low path
#

there are lots of classes in unity that use public setters and there are lots of properties that aren't explicitly tied to individual backing fields. you can also have different properties that change the same or multiple backing fields in different ways

#

this is a common use case

buoyant knot
#

because now you need to go read through code to see if you are supposed to invoke a method, call the setter, or set the backing field

buoyant knot
#

it’s ok to make public setters, but it can very easily and quickly lead to massive issues

low path
#

yeah i mean... you have to be smart about how you're designing and using your classes, sure

#

but that's always the case

eternal needle
#

You can do literally the same thing with a public setter and method

low path
#

properties definitely have pitfalls

night mural
low path
#

if you're doing too much stuff in them and they're the only way to do that thing, that can be a problem

#

but i'm not sure i'd say "avoid public setters as a rule"

pallid nymph
#

the one true rule is that you should not follow rules too strictly 😄

eternal needle
low path
buoyant knot
#

the lesson is;
public variables are like public toilets. Everything is fine until someone shits in it.

rocky canyon
#

lol, i try to make everything private and then make things public as i realize i need to

#

thats my new procedure im trying to make habit

buoyant knot
#

and I try to avoid making setters public

#

i would rather write a public method that sets for a specific case. And I am still very strict with my public setters

#

making a getter public when you realize you need to read it is fine imo

low path
#

looking through my code, in my current project, i'm rarely using public setters (or any setters at all) but in a previous project i did, public setters came in very handy. in that case, i was making a runtime inspector for modding a unity game through harmony and the UI controls that I made had a class that modified an underlying runtime value. there, how the setters operated depended on what the underlying runtime value was (determined via reflection), and i found that using a setter that did a few simple checks to determine how to modify the value worked well

buoyant knot
#

because the better you get, the more you restrict the ability to set your variables

low path
buoyant knot
#

like with this class:

/// <summary>This is affectively an Action, where the inner implementation is
/// a list to allow lots of entries to be added more easily.</summary>
public class BigAction {
    private List<Action> actionList = new();
    /// <summary>Construct big delegate with capacity.</summary>
    public BigAction(int capacity = 16) => actionList = new(capacity);

    public int Count => actionList.Count;
    public void Add(Action action) => actionList.Add(action);
    public void Remove(Action action) => actionList.Remove(action);
    public void Clear() => actionList.Clear();
    /// <summary>Invoke all the actions. Actions can be added to the delegate in the middle, but do not remove.</summary>
    public void Invoke() {
        for (int i = 0; i < actionList.Count; i++) actionList[i].Invoke();
    }
}```
low path
#

been abandoned for 4 years and nobody cares about it but it was a fun project

buoyant knot
#

i could have made that list public, but I did not, so I could make it a lot easier to track and control.

#

nothing will randomly sort my list. Nothing with randomly assign to some index in the middle, etc. And that is ok

pallid nymph
#

yes, there are many examples where you don't want a public setter 😛

#

but lets say this class had some parameter that controls how it behaves... it's quite possible you'd just want it to be a public thing 🤷‍♂️

#

say "ClearListenersOnInvoke" bool (random example 🤷‍♂️ )

buoyant knot
#

as a general rule of thumb, the more things that access an instance of the class, the more you need to restrict access

#

or very tiny data structure classes probably have a lot of public setters.

low path
#

probably could have used different classes for modifying properties or fields but... this is what i came up with and it worked i guess

#
set
{
    if (isProperty)
    {
        currentPropertyInfo.SetValue(currentComponent, value, null);
    }
    else if (isField)
    {
        currentFieldInfo.SetValue(currentComponent, value);
    }
    else
    {
        throw new InvalidOperationException("cannot set value where member is neither a field nor a property");
    }
}
#

but like this worked pretty well...

queen adder
#

Hey guys I have a problem, I'm trying to implement a knock back effect into my game but I noticed that the player movement is overriding it so it doesn't do anything, how can I fix this?

buoyant knot
#

i normally stage movement changes

summer stump
buoyant knot
#

player movement should happen in normal fixed update

#

modifiers that have to lead into it have to happen before, and things that modify after need to come after

#

but since player movement is normally followed by physics sim, whether you modify (via knockback, magnet, etc) in collision callback vs earlier in fixed update, it will all be on the same side

#

eg the order is still: playermovement => sim => knockback

queen adder
buoyant knot
#

are you trying to block playermovement entirely? or adding a knockback effect on top of the movement

#

what I described is the latter

queen adder
buoyant knot
#

ok, then what I said

summer stump
buoyant knot
#

make sure knockback happens at a point in time where you are ready for it

queen adder
buoyant knot
#
  1. make sure knockback is always applied before or always after playermovement
#

you do not want the effects to sometimes come before, or sometimes come after. Whichever you pick, it should always be the same

queen adder
buoyant knot
#
  1. avoid setting velocity directly unless you want to override everything that came before
buoyant knot
#

AddForce or related

summer stump
buoyant knot
#

if it is a kinematic RB, then you want to do like a += velocity, as opposed to just hard setting velocity to a specific number

whole idol
#

I placed this red thingy directly above. But when I play my game it always skews towards the left a little bit, why?

queen adder
#

Hm okay, i actually tried using addforce but it started working in a weird way so I stopped using it.
I'm gonna try again

buoyant knot
#

example;
my player jump modified rigidbody.velocity = new Vector2(velocity.x, jumpSpeed). So it ignores ALL changes to Y velocity that comes before it

#

but if you .AddForce or do rb.velocity += new Vector2(0,5);
this just adds movement on top of whatever you have

#

and if your control stick directly sets rb.velocity = to a specific number, then it is overriding everything. You want to not do that

queen adder
buoyant knot
#

it depends on what you do

#

a knockback effect should be an impulse force. Adds to velocity once, and then done

queen adder
buoyant knot
#

add forces ADDS force to whatever forces are already there

queen adder
#

Well but how would I create a script that makes the player move at always a constant speed, but allows for other forces to work

#

Because the issue is still that even if I add a force for the knockback the player movement just resets it back to the default movement speed

whole idol
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class WaypointFollower : MonoBehaviour
{
    [SerializeField] GameObject[] waypoints;
    int currentWaypointIndex = 0;
    [SerializeField] float speed = 1f;
    void Update()
    {
        if (Vector3.Distance(transform.position, waypoints[currentWaypointIndex].transform.position) < .1f)
        {
            currentWaypointIndex++;
            if (currentWaypointIndex >= waypoints.Length)
            {
                currentWaypointIndex = 0;
            }            
        }

        transform.position = Vector3.MoveTowards(transform.position, waypoints[currentWaypointIndex].transform.position, speed * Time.deltaTime);
    }
}

I placed this red thingy directly above. But when I play my game it always skews towards the left a little bit, why?

slender nymph
#

but you could instead just not get input for the duration of a knockback to allow the knockback forces to work then after a short duration allow input to start working again which will then override any leftover force from the knockback

#

of course tuning that timing will be fairly difficult because you want it to last long enough that the knockback takes full effect but not so long that the lack of response to input is noticeable to the player

#

or another thing you could do, which will be more complicated but likely work better in the long run, would be to create your own wrapper class for a Rigidbody that you interface with instead of the rigidbody. you can then track the amount of force input should provide as well as outside forces then combine that manually and assign the velocity using that combined force. That would give you more granular control over the forces being applied to the body while also letting you keep your input's force at a constant rate

rocky canyon
#

u could keep up with velocity..
construct ur vector before hand and pass it into the rigidbody at the end..
ud have ur movement forces and ur knockback forces..
and u add them right before u pass them into the RB
(this method would allow the knockback to influence the player but u'd still have control)
(for example if u got knocked back.. u would be able to push back using ur movement)
but if u werent holding any controls u'd get the full knockback..
oor u'd have to isolate the vectors and zero out ur movement to allow knockback to be the only force.. if thats what ur looking to do

supple citrus
#

This coroutine isn't working

#

What did i do wrong

slender nymph
#

coroutines do not delay the code they are called from

#

they only delay what is inside of them

supple citrus
#

so i just put both code lines changing the text inside of the coroutine?

slender nymph
polar acorn
meager steeple
#

!ide

eternal falconBOT
snow girder
#

how to make scalable positive fire rate

#

i jus don't get it how to do it without a cap

shell sorrel
supple citrus
#

is there a way to do this without needing to pass a parameter?

snow girder
#

well how im doing it is

#

it waits seconds 60 - firerate

supple citrus
#

This is the only time im going to use this coroutine so it seems kind of useless

snow girder
#

so there's a cap when the fire rate reaches more than 60

polar acorn
supple citrus
#

I swear i did that and it gave an error and now it isnt

#

Ur magic

shell sorrel
#

to figure out how many per frame to do, it will be a calculation based on how many you want to fire per second and delta time

snow girder
polar acorn
shell sorrel
#

yeah more or less given the first ones in the frame a head start

snow girder
#

well the weapon that i plan on using is not automatic so i don't think we'll need to worry about it exceeding one frame

shell sorrel
#

then what is the issue then

polar acorn
shell sorrel
#

if you are not worried about that problem, its a much more simple problem to solve

polar acorn
#

Honestly I don't think you'd have to deal with it being less than two frames because in order to press the button it first must be released

shell sorrel
#

well that is how UI is handled, but generally shooting is on press not release

polar acorn
shell sorrel
#

but if not worried about multiple per frame, its a simple set a field on shot to how long you want to wait in seconds, and per frame subtract delta time, and dont allow a fire again till its 0 or below

polar acorn
#

Yeah, I'm just pointing out that even if you had zero cooldown you'd still only be able to fire at a rate of one shot per two frames, so there is a cap even without programming one in

snow girder
#

or isaac

#

you can hold the button and it spits out a bullet ever 2 seconds or smth

polar acorn
#

Why did you say it wasn't

shell sorrel
#

if you want it to require a new press for each shot, but act on the press not the release

snow girder
#

oh wait

shell sorrel
#

just use a bool

snow girder
#

you're right

shell sorrel
#

reset it on release

#

so on press checks if its aloud to fire, then sets the bool

polar acorn
shell sorrel
#

release unsets the bool

polar acorn
snow girder
#

but i don't want it to be so automatic that it does like

#

5 buleets in 1 frame

polar acorn
snow girder
#

i suppose thats a cap then

shell sorrel
#

a timer then

snow girder
shell sorrel
#

make a shotDelay field

snow girder
#

have a positive value make another go down

shell sorrel
#

before shotting make sure its 0 or below

#

when you do make a shot set it to how long you want to wait

#

subtract deltaTime from it every frame

polar acorn
snow girder
#

yeah but how do we calculate the period of time

shell sorrel
#

dont evne need the bool

snow girder
#

since there are gonna be items that make the firerate go up

shell sorrel
#

yeah that is fine

polar acorn
snow girder
#

and im having trouble figuring that out

shell sorrel
#

you just adjust what you set shotDelay to

#

guess shotDuration is a better name

snow girder
#

makes sense

shell sorrel
#

dont fire when its above 0

snow girder
#

wait actually

#

what the hell is a field

shell sorrel
#

when you are aloud to fire, you set it to how long you want to wait

#

then on update you also do a shotDuration -= Time.deltaTime

shell sorrel
snow girder
#

right

#

okay thanks for your help

shell sorrel
#

so like private float _shotDuration; on your class

snow girder
#

you guys are based

snow girder
#

since the firerate is a positive number

#

and it only goes up

#

not down

polar acorn
#

I don't know what you mean

shell sorrel
#

you wnat a firerate that is like 5 shots per second

snow girder
#

so the faster you shoot the more it is

shell sorrel
#

you just have a shotDuration of 5/60

polar acorn
snow girder
#

yeah but how do you calculate that

#

like how much time should be reduced

polar acorn
snow girder
#

if it goes up by one

polar acorn
#

But multiplying by a value smaller than one also works

snow girder
#

okay you know whaty

#

i got this

shell sorrel
#
public class Gun : MonoBehaviour {
    [SerializeField] private float _fireRate = 10f;
    private float _shotDuration;

    private void Update() {
        _shotDuration -= Time.deltaTime;
        if (_shotDuration > 0) return;

        if (Input.GetButton("Fire")) {
            _shotDuration = 1f / _fireRate;
            Fire();
        }
    }

    private void Fire() {
        // todo fire the bullet
    }
}
#

something like that, untested but gives the gist

night mural
snow girder
#

bro i used an Ienumerator 😭 😭 😭

shell sorrel
#

though generally i would not define fireRate like this

#

like instead of saying 10 shots per second like that and needing to divide

meager steeple
#

I have this code to change the full screen mode to be that of the a toggle isFullscreen

{
  public void SetFullscreen (bool isFullscreen)
    {
        Screen.fullScreen = isFullscreen;
        Debug.Log("Toggled Fullscreen");
    }
}

however when i leave it in windowed, close the game, and then reopen it, it will start the game in windowed, but the toggle is still true

shell sorrel
#

i would say it waits 0.1 seconds between shots and skip that division to convert from firerate to delay

snow girder
#

its gonna sound really stupid but it's like a revolver that you hold down to shoot...

shell sorrel
#

oh so you want the delay to happen after you press the trigger

snow girder
shell sorrel
#

very simlar idea, you just start the countdown after press, then fire wehn its 0

snow girder
#

it stops after you releases

fading rapids
#

how do you reference another float from another script for example, public float sens = 50f;, and in a different script i do if(...) sens = 0;

noble forum
#

hi, may anybody tell me why in my chess game this script summons a queen after promotion correctly (1) but when i tried to change it with giving few options to the players it suddenly stopped working (2) The piece is always black and it spawns always on 1 side of the map, not where the pawn was?

slender nymph
#

show !code

eternal falconBOT
noble forum
#

Yea, i will in a sec

whole idol
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class WaypointFollower : MonoBehaviour
{
    [SerializeField] GameObject[] waypoints;
    int currentWaypointIndex = 0;
    [SerializeField] float speed = 1f;
    void Update()
    {
        if (Vector3.Distance(transform.position, waypoints[currentWaypointIndex].transform.position) < .1f)
        {
            currentWaypointIndex++;
            if (currentWaypointIndex >= waypoints.Length)
            {
                currentWaypointIndex = 0;
            }            
        }

        transform.position = Vector3.MoveTowards(transform.position, waypoints[currentWaypointIndex].transform.position, speed * Time.deltaTime);
    }
}

Does anyone know what this error is? Everything works well as intented but I just wanna get rid of this error !

shell sorrel
#

well look at line 12

slender nymph
#

and read the error message

shell sorrel
#

its a pretty good and descriptive error message

polar acorn
noble forum
polar acorn
shell sorrel
whole idol
#

I assigned them on these thingies right here

polar acorn
#

show where you've assigned them

whole idol
#

oh wait I just realized I didnt assign them

#

by adding component

polar acorn
whole idol
#

I assigned them on the red box named "Enemy"

#

And then... I assigned 2 way points in the waypoint script inside of that

shell sorrel
#

have to keep in mind, there can be multiple instances of any given script in the scene

#

and the reported error might not be for all of them

noble forum
whole idol
shell sorrel
whole idol
#

sometimes I get errors like this and then later they go away Idk why

shell sorrel
#

figure out why you have the error and resolve it

polar acorn
shell sorrel
#

you have more then one WaypointFollower in your scene

#

make sure waypoints are assigned correctly on all of them

polar acorn
# noble forum Anybody knows why?

You have a bunch of objects assigned here that you're enabling whenever a promotion happens. Why? It's going to activate whatever you dragged in, not spawn a new object

noble forum
#

Those are buttons

#

It should work like that:

whole idol
noble forum
#

The pawn enters promotion, player get to choose from 4 options as in normal chess via buttons, when he chooses one all other disappear and the selected piece is supposed to go on the tile

polar acorn
whole idol
noble forum
#

It spawns the piece and disables the buttons but piece alwais spawn in thhe corner and it is always black, when queen from first script changed colors and were on the same tile as pawn

whole idol
polar acorn
summer stump
polar acorn
#

See what values aren't what you expect them to be

noble forum
#

Well, i see that the type of piece is spawning. It is only black and spawns on a1 so it doesnt read position for some reason

polar acorn
noble forum
#

Well, piece is a pawn that is destroyed upon promotion

polar acorn
noble forum
#

The one that reached promotion

polar acorn
#

did you check

noble forum
#

Yea

polar acorn
#

How did you check?

whole idol
# summer stump Did you clear the errors and ru- ah, too slow

Oh yeah. now it's gone. But now that I run it I see something else being weird here with the movement of these enemies. The entire cube has shifted towards the right where In reality they're literally placed right above the green floors and they have the exact same positions and scales so why is it moving like that?

noble forum
#

Few different pawns went, all of them were destroyed on different tiles, then promotion spawning begun

polar acorn
polar acorn
noble forum
#

It works with 1st script, but for queen only

whole idol
#

Also the waypoints have the same X and Y position

whole idol
queen adder
#

heyyy

whole idol
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class WaypointFollower : MonoBehaviour
{
    [SerializeField] GameObject[] waypoints;
    int currentWaypointIndex = 0;
    [SerializeField] float speed = 1f;
    void Update()
    {
        if (Vector3.Distance(transform.position, waypoints[currentWaypointIndex].transform.position) < .1f)
        {
            currentWaypointIndex++;
            if (currentWaypointIndex >= waypoints.Length)
            {
                currentWaypointIndex = 0;
            }            
        }

        transform.position = Vector3.MoveTowards(transform.position, waypoints[currentWaypointIndex].transform.position, speed * Time.deltaTime);
    }
}

polar acorn
noble forum
#

The pawn is destroyed then i get to choose the button, they dissapear and a piece appears. It is black and on a1, so it doesnt reach position of a pawn

noble forum
polar acorn
queen adder
#

FUCK i got sidetracked and i didnt ask my question

#

anyways, visual studio doesnt work on linux so what should i use instead of visual studio code

noble forum
noble forum
summer stump
#

Otherwise it's gonna have to be vim 😂