#💻┃code-beginner

1 messages · Page 372 of 1

wintry quarry
#

That doesn't really change the advice given

teal viper
#

Ask them what dependencies you need to install

rocky gulch
#

ok thanks

old karma
#

ok so i feele like this shouldn't be a big deal, but maybe im overlooking.

i'm trying to make a simple editor script that will allow me to select multiple gameobjects in a child as if i were Ctrl + clicking them individually.

for the sake of just making them select, i was just trying to make them select all children

#

i can get it to select all the transforms, but it doesn't display as it should when you actually click them, and it's not quite the same objects as if i selected them manually in the inspector/heiarchy window

restive kayak
#

Can someone help me with my rigidbody player movement script? When I hold W, the player's velocity increases until they reach max speed. However, when I start pressing W and A together, I use Vector3.MoveTowards to change the player's velocity to the new direction. During this transition, the player's speed drops below the max speed until it reaches the new velocity. I want the player to maintain max speed (or increase to it if not already there) even when changing directions, like from Vector3(1, 0, 0) to Vector3(1, 0, 1).

I'm not sure what to do as I don't want to keep the players movement speed at max if they were to move from forwards to backwards.

code if anyone is interested: https://hastebin.com/share/miyapogiyi.csharp

ivory bobcat
#

Have a variable for speed and use that with your direction as the velocity

#

Where you'd increment that variable (a float) instead of some velocity (vector 3) - you'd simply be modifying the scalar or rather, the magnitude of velocity.

#
if moving
    speed increases 
velocity = speed * direction```
dry cairn
#

!code

eternal falconBOT
dry cairn
#

how come i cant jump

wintry quarry
dry cairn
#

oh how do i fix tht

wintry quarry
#

or because your gorunded check isn't working

#

Use Debug.Log and figure out which

#

or maybe jump speed is 0

#

you need to debug it

dry cairn
#

how do i debug im VERY new

wintry quarry
#

The simplest way is adding log statements to your code to see what's going on

#

If you're very new, the first thing you should have learned in Unity was how to use Debug.Log

dry cairn
#

never done tht lol just looked up how to make a character an just followed the tutorial an here i am lol getting stuck is there a free way to learn all the code i need

wintry quarry
#

!learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

dry cairn
#

thank u

lavish magnet
#

How can i make a unity slidfer follow this trail? I want the ball to slide from the ends

sweet zenith
# lavish magnet How can i make a unity slidfer follow this trail? I want the ball to slide from ...

Do you want to be able to grab and drag the slider handle, or just show it as a progress bar? This is something you'd have to decide. Then from there it will be a bunch of custom code.

Probably the easiest way is to have a circular rail image (like you have there) then put a drag handler on that. When you click and drag adjust the float value (between zero and one) and then set the handle position using local position and rotating a vector by an angle based on the value.

lavish magnet
#

Nope, not interactable*

sweet zenith
#

Oh that's easier then

#

In that case have your handle image as a child of the background image

#

Set the pivot of the background image to (0.5, 0.5), that means its origin is in it center

#

Then have the circle image as a child

lavish magnet
#

I wont lie to you i'm just a kind of conmfused

#

So using an actual slider right?

sweet zenith
#

No, no reason to do that

lavish magnet
#

No slider component

sweet zenith
#

Sliders are for interaction

#

And they're hard coded to be straight

#

You'll need to make your own thing

lavish magnet
#

Ok handle image

#

I thought that was the knob?

sweet zenith
#

Yeah the knob

#

Exactly

#

That's what I'm talking about

#

But you'll need your own code to move it around

#

Iirc the slider uses margins or anchors to move left/right

lavish magnet
#

how do i do that 😭

topaz fractal
#

can i not call a variable in the middle of a string using {}?

polar acorn
#

You need a $ in front of it

topaz fractal
#

I see, and why does that work

rich adder
topaz fractal
#

@rich adder thanks sm

abstract finch
#

is there any way to use the token variable in the second switch here without renaming it? They are in different switches so I dont understand the clash

ivory bobcat
#

Use the curly braces with the cases to isolate the statements

wintry quarry
#

Or declare the variable before the switch

#

although honestly I'm struggling to see the point of this switch

#

the code is identical @abstract finch

#

if it's just going to be the _timeSinceMeleeTokenAssigned = _standardTokenAssignCooldown line that changes, I would just put that particular line in the switch and do the rest outside anyway.

versed light
#

i created a scriptable object asset its residing in a folder and im trying to get it from the asset database by type but its not finding anything i keep getting 0 results:

string[] result = AssetDatabase.FindAssets("t:TestDatabase");
Debug.Log(result.Length);

my scriptable object class is defined as public sealed class TestDatabase : DatabaseAsset

does it matter where i place the asset in the projects directory? currently the created asset is in Assets/Game Assets/test.asset

abstract finch
abstract finch
thorny prawn
#

how can i render only the object of a plane and down like if camera is up
imagine my main player is in a plane of XY axis i want to render only object of that plane based on Z axis but if camer is on top or in +Z so Object of the Current plane and -Z should render

wintry quarry
thorny prawn
#

how can i explain it idk
but in code the object above player should'nt be rendeer if camer is on Z axis facing down from + to- direction or vice versa
similarly in different axis for if camer is facing player from + to - direction of X or Y axis

wintry quarry
#

Or use the Near Clipping Plane distance on the camera to exclude them

zinc shuttle
#

!code

eternal falconBOT
zinc shuttle
#

How can i spawn only 1 ball by only 1 touch?

zinc shuttle
#

its instantiating many balls, what alternative method i can use

wintry quarry
#

See the code example

#

Also this:

            CanPlace=false;

        }
        if(CanPlace==false)
        {
            Debug.Log("cant place");
        
            Invoke("delayedcanPlace",3f);
        }```
Is crazy
#

Why not just:

            Instantiate(Ballz, spawnPosition, Quaternion.identity);
            CanPlace=false;
            Invoke("delayedcanPlace",3f);
        }
}```
ivory bobcat
zinc shuttle
#

problem is with instantiating, its spawning multiple balls even with given delay, will it fix this?

wintry quarry
zinc shuttle
wintry quarry
#

Becasue you're starting 8 bajillion Invokes

#

that all set CanPlace = true

#

so this code suggestion alone should fix it

zinc shuttle
#

ok let me give it a try

#

ok it worked perfectly

restive kayak
# ivory bobcat Have a variable for speed and use that with your direction as the velocity

I tried this but couldn't figure out how to maintain speed when changing from moving forward to horizontally in a controlled manner, the only thing I could thing of was multiplying the new velocity vector by the current speed but doing that made it so if I was below the max speed I wasn't increasing velocity. I feel like there is a simple solution I'm not seeing.

modest oar
#

just curious about why this freezes my project

    IEnumerator batteryDrain()
    {   while (true)
        {
            if (flashlight.enabled == true)
            {
                yield return new WaitForSeconds(2.5f);
                Battery = Battery - 0.1f;
            }
        }
    }
burnt vapor
#

If flashlight.enabled is false it will just restart the while loop infinitely

#

To fix it, add a delay in an else statement

gaunt ice
#
 IEnumerator batteryDrain()
    {   while (true)
        {
            if(bool that is false){}
        }
    }
modest oar
#

oh ok, thanks

burnt vapor
#
    IEnumerator batteryDrain()
    {   while (true)
        {
            if (flashlight.enabled == true)
            {
                yield return new WaitForSeconds(2.5f);
                Battery = Battery - 0.1f;
            }
            else {
                 yield return null;
            }
        }
    }
#

This waits 1 frame @modest oar

modest oar
#

thanks

gaunt ice
#

btw you should take the "duration" into account

float time_before=Time.time;
yield return
float time_after=Time.time;
Battery-=0.1*((time_after-time_before)/2.5f);
#

though 2.5f should be a relatively big number vs 1000ms/60frame

storm pine
#

Or even better just put the functionality on the Update() using Time.deltaTime so you avoid the infinite loop.

private void Update()
    {
        if (flashlight.enabled) //You don't need to compare if it's true since it's a boolean itself
        {
            drainTimer += Time.deltaTime;
            if (drainTimer >= drainInterval) //drainInterval 2.5f in your case
            {
                Battery -= drainAmount; // 0.01f in your case
                drainTimer = 0.0f; // Reset the drainTimer
                if (Battery <= 0.0f) //Extra funcionality, turning of the flash when it runs out of battery
                {
                    flashlight.enabled = false;
                }
            }
        }
frank zodiac
#

[field: Serialize] or [SerializeField]?

keen dew
#

[field: Serialize] throws an error so [SerializeField]

#

Use [field: SerializeField] for properties

frank zodiac
#

oh okay

#

thank you

night raptor
#

Yup. Often times serializing the backing field of a property isn't a great idea though (if we talk about exposing properties to inspector) because then the change in inspector won't go through the setter of the property. In context of serialization on save and load systems for example, serializing the backing field is fine

rich seal
#

Can anyone help me with my player's movement script? My player walking to automatically moves to the right and I want it to automatically move to the right as well with a and d keys. How can I do it?

signal spruce
#

is there any way to close quickly a lot of scripts in visual studio?

teal viper
signal spruce
#

or all

teal viper
#

middle click all of them except the one you're in🤷‍♂️

#

I guess there are also options in the context menu

#

Close other tabs sounds like what you need

signal spruce
vestal adder
#

hi im wanting to make some complex enemy ai for a 2d top down game and im not sure where to start, like should i use navmesh agents, a* or something elsee

fossil drum
#

AI and pathfinding are not the same thing. But sure, both of those will fix your pathfinding problems.

vestal adder
#

what would you say ai would be in that context

fossil drum
#

AI does things, pathfinding moves things.
AI could move somewhere sure, but it's more then just that, it can also flank, or shoot, or pick up weapons, or solve any other problem you can think of.
But simple AI can just move to player and attack when close for example.

#

And there are tonnes of ways to make an AI.

bitter spruce
#

does anyone know, for Platform Effector. How do i make it so that my player does not collide with the sides of the platform. Just the top when the player stands on it. Im doing a 1 way platform but when the player enter the sides of the platform, it just dosent allow my player to walk through it

vestal adder
#

yeah i see

#

i think to start i wanna make good pathfinding

fossil drum
#

That's a good idea, fix the problem in smaller pieces.

bitter spruce
#

liek i can jump through from the bottom and land at the top but the sides are making me collide

outer coral
#

on 180?

#

objects collide with things at certain directions that surface arc property on the effector defines at what angle threshold it should register the collisions

#

if you left it at 180 then it makes sense the sides would collide, change it to something like 90 for a better result

jovial forge
#

Currently having a weird issue with the old input system. There is input being given from somewhere and I can't figure out where. I have unplugged all of my controllers from my PC, and confirmed this with joy.cpl. When I hit play, horizontalInput becomes -1 and verticalInput becomes 1, even though I am not providing any input

public class PlayerController : MonoBehaviour
{
    public float speed = 5.0f;
    public float turnSpeed;
    public float horizontalInput;
    public float verticalInput;

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

    // Update is called once per frame
    void Update()
    {
        horizontalInput = Input.GetAxis("Horizontal");
        verticalInput = Input.GetAxis("Vertical");

        transform.Translate(Vector3.forward * Time.deltaTime * speed * verticalInput);
        transform.Translate(Vector3.right * Time.deltaTime * turnSpeed * horizontalInput);
    }
}```
deft grail
wintry quarry
jovial forge
jovial forge
jovial forge
wintry quarry
outer coral
jovial forge
wintry quarry
#

Try restarting your computer?

jovial forge
jovial forge
swift crag
#

specifically my wireless xbox controller on my macbook

jovial forge
#

Wonder if it was some ghost input from one of my many custom flight sim controllers

dusty silo
#

Can I have an object that only exists in the code have a Collider2D?

swift crag
#

I don't know what "only exists in the code" means

#

Collider2D is a component. Every component must be attached to a game object.

#

So you can't just have a loose Collider2D that isn't attached to a game object, no

dusty silo
#

Okay, thanks

swift crag
#

are you trying to do something in particular?

modest dust
#

If, for some reason, you're creating a GameObject from zero via code, you can just call AddComponent on it

molten robin
#

is there a reason for why the _defaultPosition goes so high even though in editor the objects transform is this?

graceful crescent
#

Is this GO a child of any parent GO?

polar acorn
#

The transform you see in the inspector is local position. You're logging world position

cosmic oxide
#

Guys, So I have loaded a scene "InputSys" as an additive and I am trying to unload the same using var operations =SceneManager.UnloadLevelAsync("InputSys"); . The function is returning null. Can someone look into this? Will really appreciate the help.

polar acorn
swift crag
#

(note that it doesn't run "on a new thread")

cosmic oxide
cosmic oxide
swift crag
#

I'd sanity check by making sure you don't call WaitForUnloading anywhere else

#

shift-f12 while the name is selected

swift crag
#

although, I would expect at least part of the async scene loading process to include loading stuff from disk on other threads

#

(you can watch the profiler's timeline view to see exactly what's going on )

cosmic oxide
#

Well I found this on forum xD

swift crag
#

oh, yes, you were trying to do that

cosmic oxide
#

Yup haha

swift crag
#

"last loaded scene" meaning the only one left, not the most recently loaded one

#

Note: It is not possible to UnloadSceneAsync if there are no scenes to load. For example, a project that has a single scene cannot use this static member.

this line is very weirdly worded

#

it should just say "if there's only one scene loaded, you can't unload it"

cosmic oxide
#

Well I have multiple scenes loaded

swift crag
#

i've loaded and unloaded a scene without loading any other scenes in-between

cosmic oxide
#

I fixed it by calling the UnloadLevel as as coroutine.

#

Is it possible that previously it didnt completely finish loading the scene in the memory?

#

Thats why I bumped into null reference exceptions

swift crag
#

if you try to unload the scene before the scene ever loads, it would break

#

but there's no point where a scene is "partially loaded"

#

by that I mean partially set up

#

Unity loads all of the assets, then synchronously activates the new scene

#

so there's no point where it's..."half there"

karmic river
#

Hello guys, am new to Unity, I created this function in a script that returns a boolean value and now i want to use the value returned by this function in another script in an if statement

swift crag
#

You will need a reference to this component.

karmic river
karmic river
swift crag
wintry quarry
# karmic river

Why not just return birdIsAlive;? No need for an extra if statement here

karmic river
karmic river
#

Oh waittt now I understand

swift crag
#

Okay, so whoever wants to ask if the bird is alive needs a BirdScript

karmic river
#

I have to write BirdScript rather than LogicScript

swift crag
#

it tried to get a LogicScript component from the object tagged "Bird"

#

so it gave you nothing

karmic river
#

Why is this if statemenet returning error

#

It says this

swift crag
#

You're trying to compare the method itself to true

#

you need to call the method

karmic river
swift crag
#

the method returns a bool, which you can compare to true

karmic river
#

It is now working, thanks man 🙂

#

I declared a bool variable rather than the method itseld

swift crag
#

why not just..call the method?

#
Bird.IsTheBirdAlive()
vestal adder
#

i am trying out a* and downloaded the latest free version from the website but it came with these errors, and i dont understand the error messages on how to fix them

swift crag
#

read the warning

#

it tells you what to do

#

oh, fair enough, you just didn't grok it

#

Check here:

#

You want to switch from Web to Windows, Mac, Linux

vestal adder
#

thank you fen

#

am i already on it?

swift crag
#

You are, yes

#

Ah, I suppose you need to go fix this in the Player settings instead

#

well, this should really be something that the asset creator fixed by having it connect securely...

#

what asset is this?

vestal adder
#

i am fairly sure its a legit thing

#

if theres no issues with turning that off then its fine

swift crag
#

it'd be this setting, found in the "Other Settings" section of the Player settings

vestal adder
#

thanks i couldnt find it

fluid kiln
#
    {
        SceneManager.LoadScene(sceneId);
    }```

Why is this not working? i tried with scene name aswell
vestal adder
#

think it has to be in quotations

#

the scene name

fluid kiln
#

oh tysm!

vestal adder
#

welcome

swift crag
#

that'd be if the scene was literally named "sceneId"

#

or "sceneName" or whatever

#

if sceneId is 0, then this should re-load the starting scene

fluid kiln
#

but scene name is a variable

#

that's why no ""

swift crag
#

correct, since "this is a string literal"

#

you would not quote variables

#

I would check that the code is running at all

#

add a Debug.Log statement to the method

vestal adder
#

it does work now

#

says itd be insecure if its always allowed so i put in development builds

#

though i think that it would crash in a built game in that case

swift crag
#

this code probably doesn't run in the built game at all

#

I'd just turn off the update check, if that's an option

vestal adder
#

it is just to check for updates it looks like

#

yeah

fluid kiln
swift crag
fluid kiln
#

ooooooh

#

its case sensitive, mb, cuz if i use caps unity automatically puts a space in there with inspector

#

tysm! it all works now!

final kestrel
#

Is it better to save/load the inventory? or like save both the items and the inventory and deserialize them on load? I do not know how to save the inventory.

final kestrel
#

The Item part just confuses me

willow scroll
final kestrel
willow scroll
#

How do you want to save the inventory?

final kestrel
#

Like serialize the contents and the slots somehow and load them back in.

willow scroll
#

You want them to stay persistent when loading the game again?

final kestrel
#

Yes.

willow scroll
#

You would usually use json for this

#

Have you tried that out before?

final kestrel
#

Yes I have the data handler already for that It just does not deserialize the scriptable objects

woeful dawn
#

prefer saving just items and than populate inventory

final kestrel
woeful dawn
#

like it was said use json or any other method of making persistans data save. read that when you need to load them, and populate inventory

#

remember that unity serialization is not a way to make persitant runtime data save

final kestrel
#

So I individually save the items. I give them all an ID. Then I give the inventory an ID. Then read the item data and uhhj

willow scroll
woeful dawn
#

SO behave slightly different when game is build in comparison to Editor runtime.

final kestrel
willow scroll
willow scroll
woeful dawn
#

i think at this point its about data virtualization...
u need to define structare of save data that will let you reconstruct objects again

final kestrel
#

Well we can keep the player data in the persistentdatapath. And when scene loads it deserializes (json) then it all works.

willow scroll
#

You would usually have a class, which contains a List of your items. The class can be casted to json and back

final kestrel
#

That class is inventory then?

willow scroll
woeful dawn
#

honestly don't know common approach, but for me saving system is separate thing

final kestrel
#

So I make an Inventory class Which holds the Item(SO) list

#

and also the inventory slots right?

willow scroll
#

You then get the List of Items from your saved json, which you then enumerate through to add them to your Inventory once more

final kestrel
#

the inventory slots hold the inventory items. Inventory items are scriptable objects fed into the InventoryItem.

willow scroll
final kestrel
#

Yeah they are just images.

willow scroll
#

Then this should be a great approach

final kestrel
#

Basically what you feed in them just changes sprite and type

#

Uh so just to be clear and I do not do anything wrong. I make class Inventory. Should I hold the scriptable object list? or just go with Inventory slot and inventory Item list?

spiral narwhal
#

I have a global reference that should be used for every object that has the respective script on it. For example:
[SerializeField] private Material _globalFlashMaterial;

However, I feel like I should handle this differently... Like have it be a public static reference. Or maybe I should use the addressables feature here? What's the best way to handle such references?

willow scroll
woeful dawn
#

either use addresables or put Mateterial in Reources folder and than u can make static helper method to retrive that at any point

willow scroll
#

The static class holds the methods and other logic, I usually call them SomethingUtility.

#

The another class should be used to be parsed to json

#

This is the class you will get when deserializing the json

woeful dawn
#

exatly! keep single resposibility! create class for handling persistence of data, and let inventory just be inventory...

final kestrel
#

Okay I will try. Never nested classes like this so im a bit confused 😄

willow scroll
willow scroll
woeful dawn
#

its not nesting... its basic composition

final kestrel
#

I see

willow scroll
#

Like... a Coroutine?

woeful dawn
#

netsing would be to define class in a class... with have its use cases... but not here xD

final kestrel
#

Well all right. It kinda got me confusing cos I have 3 things in my inventory. Item (this is a scriptable object which feeds its data), Inventory slot and Inventory Item which is inside the Inventory slot hhaha

willow scroll
#

Yes, I would usually define those classes simply in a single script

public static class InventoryUtility { }

public class InventoryData { }
#

Note that this doesn't reffer to your previously sent message

final kestrel
#

Hm okay. I think i got it

#

So uh the utility class in my case is for writing and reading jsons

woeful dawn
#

in this case i belive so...
if there is more things that would requre persistancy i would recomand just making small generic system for that

final kestrel
#

Hm actually yes. I can hold player data. I just followed a tutorial from git-amend. It binds data between playerData and the actual player.

eternal needle
willow scroll
woeful dawn
#

man you getting so much helping love xD

final kestrel
#

Yeah haha. Its kind of confusing me a bit.

#

thanks for all the answers

woeful dawn
#

well there is more than 3-4 ways do it it so sure it will be confusing xD

willow scroll
final kestrel
#

Just the part that i should or shouldnt be saving scriptable object data is kind of unclear because I read you need some other stuff to read SO data

willow scroll
# final kestrel Yeah haha. Its kind of confusing me a bit.

I'm not saying that the approach I have mentioned is the only one, but that's what I would use.

  • A static utility class for adding the Items to your class InventoryData
  • A non-static class to handle the serialization and deserialization of jsons. Make sure to access the paths using Application.dataPath
woeful dawn
eternal needle
stuck palm
#

how does a singleton actually work? How can I reference a static class as if it was a normal class?

final kestrel
#

Ah okay I already have a non static class called FileDataHandler. Which just has a serializer dependency and acts upon it. Reading and writing to json

willow scroll
eternal needle
woeful dawn
final kestrel
eternal needle
#

It handles all of it for u

swift crag
woeful dawn
swift crag
#

I have a lot of read-only information that lives in scriptable objects

#

I chose to serialize them by ID and to then look them up by that ID when deserializing

lethal swallow
#

https://pastebin.com/RcxvZmFL enemyhealth [fricked up] code
https://pastebin.com/e0NE3Tfc collisionDetection

when I try to write enemyhealth = enemyhealth - 10;, i get this error:
[image attached: image.png]

swift crag
final kestrel
# woeful dawn wait i think i got you... do your SO even change state or they just have for exa...

They do not change. I apologize for not being clear enough. Let me explain it. I have a simple hotbar. In the hotbar I have InventorySlots which are just sprites. In the InventorySlot I have InventoryItem (which are also sprites). I have 4 Item types as scriptable objects. This SO just has ItemType enum and Image. I feed its image into InventoryItem with a method. I want to be able to save the inventory with all its items and load back in with that state.

swift crag
#

You could also just serialize the IDs manually and then look them up yourself

woeful dawn
#

ok so you only need to save information about what have to persist... in your case it can just be id of SO + index in invetory sapce

polar acorn
final kestrel
woeful dawn
#

you want to get SO's by ids and ppulate invetory with them at given index

lethal swallow
#

sorry, i typed the line after the pastebin log

polar acorn
lethal swallow
polar acorn
lethal swallow
swift crag
woeful dawn
lethal swallow
final kestrel
polar acorn
#

you're trying to use a variable you have never made

lethal swallow
swift crag
lethal swallow
#

I'm trying to access the public variable

woeful dawn
polar acorn
lethal swallow
final kestrel
polar acorn
lethal swallow
#

public float enemyhealth; in the pastebin

polar acorn
#

Which instance of the EnemyHealth script do you want to get enemyhealth from

#

This is a component that could be on thousands of objects for all the script knows

#

which one do you want

lethal swallow
polar acorn
woeful dawn
polar acorn
#

I'm asking which EnemyHealth (component) you want to get the float enemyhealth from

lethal swallow
#

ahhh

polar acorn
lethal swallow
#

i've currently set it up so that when Z is pressed healt goes down

#

*as seen in the mentioned linked scripts

woeful dawn
#

all those offcial discord communities always lack voice chats.... i get it would be extreamly hard to moderate thou

#

and sometime it would be easier to just share screen :/

lethal swallow
# polar acorn So then you need to reference that object. https://unity.huh.how/references

so sorry if what i'm saying makes no sense, but:

i've set the slider to always equal the enemyhealth constantly in the update in the enemyHealth file void Update() { if(enemyhealthSlider.value != enemyhealth) { enemyhealthSlider.value = enemyhealth; }

i've set it up so when Z is pressed enemyHealth goes down if (Input.GetKeyDown(KeyCode.Z)) { enemytakeDamage(10); }
[these both are in this pastebin: https://pastebin.com/RcxvZmFL]

all i want to do now is decrease the enemyhealth when a collision is detected.

eager spindle
#

decrease enemyhealth when collision is detected?

#

you can look into OnCollisionEnter, then compare the tag from there

weary egret
#

Why might I be getting this error when trying to LinkWithUnityAsync

[Authentication]: Request failed: 400, {"detail":"external token not provided","details":[],"status":400,"title":"INVALID_PARAMETERS"}

I do it after:

await UnityServices.InitializeAsync();
await AuthenticationService.Instance.SignInAnonymouslyAsync();

Access token is null here however

var accessToken = PlayerAccountService.Instance.AccessToken;
await LinkWithUnityAsync(accessToken);
eager spindle
#

external token not provided

#

which line is this from?

#

looks like the last line, could you check if accessToken is null

#

huh

weary egret
#

Shouldn't it be populated from SignInAnonymouslyAsync?

lethal swallow
#

thanks

eager spindle
#

yes it should but its not

#

prob because it might not be awaiting correctly

#

ill go check the reference

#

are other variables null like AuthenticationService.Instance.PlayerId?

#

the docs actually put this in a try/catch error which can give you help on if the sign in was successfull

weary egret
polar acorn
lethal swallow
#

tysm for sticking with me and my annoying self

jade trout
#

Hello friend, I was wondering if someone else gets this error when trying to follow the documentation for mlagents unity?
I am following this documentation: https://github.com/Unity-Technologies/ml-agents/blob/develop/docs/Installation.md
And the error happens when I run this command: python -m pip install ./ml-agents-envs

GitHub

The Unity Machine Learning Agents Toolkit (ML-Agents) is an open-source project that enables games and simulations to serve as environments for training intelligent agents using deep reinforcement ...

magic panther
#

I asked him about creating an object. Is he yapping?

#

ofc this is plain cs, not unity one

spare gate
#

why does PrizeClick not show up in the On Click() menu?

wintry quarry
#

UnityEvent inspector only supports one parameter

spare gate
#

ah

#

is there a way i can use 2?

wintry quarry
#

serialize the parameter separately

summer stump
wintry quarry
#
public int price;
public GameObject delete;

public void PressButton() {
  PrizeClick(price, delete);
}``` @spare gate
spare gate
#

i dont understand

#

oh nvm

magic panther
spare gate
#

so i should call a seperate function inside the pressButton function?

magic panther
#

in js that's simple as hell, dunno about cs

wintry quarry
#

They're called classes

#

(or structs, but that can wait)

summer stump
#

If you mean a GAME object, then that is a little different. You likely would want to use Instantiate on a prefab reference

woeful dawn
mellow shuttle
#

Hi. What is the best way to make HP recount? Which will be secured and easy?

summer stump
woeful dawn
#

if you exclude actual behind scenes stuff witch are two separate paradigms in terms of constructor they are fairly similar if we think just syntax... althou if i remember js lets define object fields inside constructor

summer stump
mellow shuttle
#

when someone hit player or enemy

summer stump
#

But yeah, making a TakeDamage method is very easy

magic panther
#

Something more comfortable to use than like 5 variables with the same prefix to differenciate

#

is what I mean

summer stump
magic panther
#

dashBar.progress.target or dashBar.progress.current feels better than combining all

mellow shuttle
#

Ok. It is good way to make public takeDamage() method?

magic panther
woeful dawn
magic panther
#

in js that's

const dash = {
  load: {
    progress: 0,
    target: 60
  },
  finishEase: {
    progress: 0,
    target: 60,
    onFinish: () => {
      blahblah
    }
  }
}```
#

how do I translate this into unity cs

woeful dawn
magic panther
#

yes I do, but there will be more and each will have different structures

#

writing an extendable base class would be futile due to the fact that I'll change, cut and add stuff separately to each

#

just, how can I create an object with properties of different values, is what I need

#

an example would be easiest for me to understand

#

like 5 lines

#

or something idk

#

spare change ahh problem

woeful dawn
#

well its not dynamic languege and if you can't structure it than maybe you should redesign it ?

#

you can use stuff like dictionary...

#

remeber OOP by desing will create alot of code... its normal to have many classes.

timber tide
woeful dawn
wintry quarry
timber tide
#

Usually if you want to do some sort of modulated code, you're thinking of composition

#

declare what you need, if you don't use them then don't initialize them and check at runtime

swift crag
#

i am thinking about how i'd translate this

woeful dawn
#

load is field with : {
progress: 0,
target: 60
}, object

swift crag
#

well

#

yes, i can tell

#

but what does it mean?

#

I can't really understand what the design intent is here

woeful dawn
#

dynamic languages support something like Anonymus objects... you dont need to define structure like class u can just create object on fly

swift crag
#

i am (painfully) familiar with how that works, yes

wintry quarry
#
public class AnimationAction {
  public int progress;
  public int target;
  public Action onFinish;
}

void Example() {
  List<AnimationAction> dashActions = new() {
    new AnimationAction() {
      progress = 0,
      target = 60
    },
    new AnimationAction() {
      progress = 0,
      target = 60,
      onFinish = () => {
        // blahblah
      }
    }
  };
}```
Something like this @magic panther
mellow shuttle
# timber tide Well, how would you do damage otherwise? ;p

I think to make empty object with collider in enemy and when attack scan it for player entries. If player entered while attacking, enemy should call public player method TakeDamage(int damage) where hp will be reduced. Same for player

woeful dawn
timber tide
woeful dawn
#

sorry bro, i am getting slow at late houers xD now when i read it back if feel awkwardly annoying xD

timber tide
mellow shuttle
#

Thanks

stuck palm
#

is it more expensive referencing another class's variable as opposed to your own variables?

summer stump
wintry quarry
#

it's the same

#

because every time you reference your own you are actually doing this.var
this.var and that.var are the same cost, because this and that are just references

woeful dawn
#

yee i got it now, makes me feel little stupid, but also realize that I may should go to sleep xD

stuck palm
rocky canyon
#

but i still dont see where u set that bool to true anywhere...

#

and also not seeing where u actually have ur crouch input

#

Input.GetKeyDown(crouchKey){//make player crouch like where is this code?

#

somewhere else?

#

if it is.. ur gonna need to copy the input and also keep track of it in this script.

#

oor reference this script and set teh bool to true and false thru the other script

#

i think u might be doing ur crouch stuff in some animator controlling type script..

#

if thats the case read the bits above ^

magic panther
#

Why am I getting an error here?

#

both of these variables are floats

wintry quarry
#

so you can't put a float in it

magic panther
#

so what do I do

hollow dawn
magic panther
#

how can I apply the changes

summer stump
#

To make it a float, instead of double

wintry quarry
#

just like the other one right above it you have

magic panther
#

somehow it's locked at 1

#

why is it locked at one

sterile radish
#

how would i fill up a bar based on a timer in a coroutine?

wintry quarry
#

smoothly? Stuttery?
linearly? Some kind of easing function?
depending on some other variable?

sterile radish
#

linearly

wintry quarry
#

just a while loop, with a yield return null, and proper use of Lerp

sterile radish
#

oh okay, thanks!

stiff fjord
#

Assets/scripts/movement.cs(49,45): error CS0103: The name 'force' does not exist in the current context

summer stump
#

You can SET it in the method

#

So, just remove float right before force

stiff fjord
#

ok

summer stump
#

And add public float force up top

stiff fjord
#

doen thanks!

#

now the boat doesnt move at all

stiff fjord
summer stump
summer stump
stiff fjord
#

nvm

#

i figured it out

ivory bobcat
#

Is your ide configured?

sick jay
#

What's the best way to go about saving the state of collectible items between scenes?
ex: One scene has a frying pan that you can collect. once you collect it, it disappears. however, currently, it reloads if you leave the area(load another scene) and come back. should i make an ItemManager of some kind that keeps track of that and destroys the already collected gameobjects each time the scene is loaded? or is there a better way

summer stump
outer coral
#

if you dont want it to come back between runtimes you'll also need a save file

sick jay
outer coral
#

It can be tricky

eternal needle
# sick jay yes I gotta relearn that, when I tried to do it with something else(saving a sim...

Theres tons of save system tutorials out there, ideally find one using Newtonsoft. Just a note if you save to file, you'll still need some item manager which exists at runtime. You dont want to pickup the pan in game and then immediately write to file. This should simply set a value on your item manager, for example a bool to true or false. Then later like if the user saves or if you change scenes, save the data. File operations are relatively slow

sick jay
shell herald
#

is there a function that activates once the object the script is on is activated?

cosmic dagger
shell herald
#

works thx

neat scarab
#

hey! im doing a simple fishing game for a university class and wanted to know if anyone has some good tips for doing simple coding like the contact between the fish hook and the fish, movement of the boat etc :) thank you

timber tide
#

depends how much realism you want

eternal needle
# sick jay sounds good. how does saving things to a file work in the editor? will pressing ...

not sure what you're asking tbh. writing to a file works the exact same way as in a build, and same way in a console application. pressing play/stop has nothing to do with it. if you save data, then load it from file then the data will be set.
https://docs.unity3d.com/ScriptReference/Application-persistentDataPath.html
the only difference is where the persistent data path points to depending on your build or if in editor

neat scarab
timber tide
#

if you want some more realism, only allow velocity somewhere in the forward direction

eternal needle
# neat scarab not a lot actually, the game is rather cartoonish

A lot depends how you want the game to actually play, try and think of that first and really the logic comes easily. Like most games dont really have fish swimming around looking for food and getting hooked. If you do want this, then you'll need some basic fish ai. Most games just use a random chance to catch one and that's all, then play some animation

neat scarab
neat scarab
#

it's in pixel art and most of the art is done

timber tide
neat scarab
#

never heard of unity documentation

#

will look into that as well

spare mountain
neat scarab
spare mountain
ember tangle
#

Is there a wrong way to write a command in the command pattern? How complex should a command be on average?

#

I have a command inheriting from a command interface and it contains a lot of methods, im not sure if this is best practice

sterile radish
worthy merlin
#
NullReferenceException: Object reference not set to an instance of an object
UnityEditor.Graphs.Edge.WakeUp () (at <cd7e7093392847c5af50f12a53ad0586>:0)
UnityEditor.Graphs.Graph.DoWakeUpEdges (System.Collections.Generic.List`1[T] inEdges, System.Collections.Generic.List`1[T] ok, System.Collections.Generic.List`1[T] error, System.Boolean inEdgesUsedToBeValid) (at <cd7e7093392847c5af50f12a53ad0586>:0)
UnityEditor.Graphs.Graph.WakeUpEdges (System.Boolean clearSlotEdges) (at <cd7e7093392847c5af50f12a53ad0586>:0)

I've been getting this error every time my Unity reloads after a script update, none of my scripts are failing to work and all of the object assignments seem correct. None of my scripts are named like anything in the error either. Very confused how to resolve this rn...

slender nymph
deft grail
slender nymph
worthy merlin
slender nymph
#

Just having it open in general. You can typically just ignore that error.
the bit about UnityEditor.Graphs.Edge.WakeUp shows it is happening due to a graph editor window and the animator is the usual suspect for that, however any graph editor window can probably produce that error

worthy merlin
#

Understood, I shall ignore the blinking red light 🫡

notlikethis

#

restarting unity did remove it from poping up for now

slender nymph
#

The animator is easily startled. It will soon be back and in greater numbers

worthy merlin
#

Also, need some advice. I need a charge up animation for my player that will change its duration based on the weapon that fired (matching a firerate in seconds variable). My hope is for it to run the animation until the weapon recharges and repeats.

Would it be better to do this with the animator or manually changing the sprites myself in code?

wheat wave
#

either works

#

it'd be silly to use both methods concurrently imo

#

you can use a short animator state and have it loop while a bool is true

slender nymph
#

It really depends on how you want to handle it, there's hardly ever a "best" way to do so. However my suggestion would be to have 3 animations for it, the first is the start up of building the charge, second is a looping one that's just building charge or whatever, and the third is the end of building the charge when it "completes". This solution allows you to stay in that charging state however long you need since it loops the middle of the full animation and can transition into and out of it.
Of course it also depends on how you want it to look as looping the charging part only works if the visual part doesn't change much based on charge percent or whatever

worthy merlin
#

My confusion is that I have the variable that says the time in seconds. But how do I feed this to the animation controller?

#

Maybe Motion Time?

sick jay
umbral bough
#

Hi, I've been struggling with this one for quite a bit.
When I separate inputs and manually call Open() and Close() instead of Toggle() it works fine.
However, the Toggle() function somehow executes Close() and Open() if the menu is already open.
Am I just being incompetent rn and this is normal or is this something weird?
Script I am calling it from:

        public void Update()
        {
            if (Input.GetKeyUp(KeyCode.Escape)) _radialMenu.Toggle(_pauseMenuContent);
        }

Relevant part of the Menu Script:
https://gdl.space/abuwukelab.cs

flint tendon
#

hey there, i have a png and i want to take certain parts of it out and use them is that something i can do?

wintry quarry
wintry quarry
#

not a code question

flint tendon
#

so theres no way of me doing it in unity?

wintry quarry
#

There's a way to do everything

umbral bough
wintry quarry
#

but with your vague description, sounds like photoshop is your best bet.

worthy merlin
wintry quarry
umbral bough
wintry quarry
#

put a breakpoint in Open and CLose

#

see what the stack trace is for each

#

somewhere along the line something is triggering it, probably a listener for the radial menu or something

umbral bough
#

don't have any, wrote the whole thing myself, only thing calling Toggle()/Open()/Close() currently is the function I provided

#

I'll do the debugging tho

#

I might've figured it out 🤦‍♂️

#

it was me being incompetent afterall

#

and you were in fact right, I did call the Close() function from this script aswell and completely forgot about it 0_o

jagged hare
worthy merlin
jagged hare
flint tendon
#

Assets\Scripts\PlayerController.cs(22,20): error CS1061: 'Weapon' does not contain a definition for 'Fire' and no accessible extension method 'Fire' accepting a first argument of type 'Weapon' could be found (are you missing a using directive or an assembly reference?)
i am getting this error in my code

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

public class PlayerController : MonoBehaviour
{
    public float moveSpeed = 5f;
    public Rigidbody2D rb;
    public Weapon weapon;

    Vector2 moveDirection;
    Vector2 mousePosition;

    // Update is called once per frame
    void Update()
    {
        float moveX = Input.GetAxisRaw("Horizontal");
        float moveY = Input.GetAxisRaw("Vertical");

        if(Input.GetMouseButtonDown(0))
        {
            weapon.Fire();
        }   

        moveDirection = new Vector2(moveX, moveY).normalized;
        mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    }

    private void FixedUpdate() {
        rb.velocity = new Vector2(moveDirection.x * moveSpeed, moveDirection.y * moveSpeed);

        Vector2 aimDirection = mousePosition - rb.position;
        float aimAngle = Mathf.Atan2(aimDirection.y, aimDirection.x) * Mathf.Rad2Deg - 90f;
        rb.rotation =  aimAngle;
    }
}
``` any help
spare mountain
eternal falconBOT
flint tendon
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Weapon : MonoBehaviour
{
    public GameObject bulletPrefab;
    public Transform firePoint;
    public float fireForce = 20f;

    public void fire()
    {
        GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
        bullet.GetComponent<Rigidbody2D>().AddForce(firePoint.up * fireForce, ForceMode2D.Impulse);
    }
}
spare mountain
#

it IS case sensitive

#

take another look

flint tendon
#

oh shit thank you

spare mountain
#

np

worthy merlin
dry cairn
#

can someone help me understand this ik i have the right answer cuz i already failed once but it was for a challenge i couldnt really do on the course so i never really got an understanding of it

rich adder
dry cairn
#

so does that mean it wont start at 0 anymore an itll start at 5?

rich adder
#

this is an array with 5 float numbers

dry cairn
#

i have no idea im still kinda confused with arrays

rich adder
dry cairn
#

i was just reading it

#

ok can i bounce off u wat my brain has interperated tht as?

#

ok this sets the what is in the array -------public GameObject[] animalPrefabs;
an this pull from tht array of animal prefabs -----Instantiate(animalPrefabs[animalIndex], spawnPos, animalPrefabs[animalIndex].transform.rotation);
an this specifies in tht index of the array that i want to randomize the animal spawned starting with 0 to how long the index is?

#

int animalIndex = Random.Range(0, animalPrefabs.Length);

dry cairn
#

ah ok thank u for some reason i had so much trouble with tht

rich adder
#

yeah tricky at first but they are powerful, keep practicing using them eventually they will be easy to deal with

dry cairn
#

so the array in the pic has 5 different floating numbers

rich adder
#

indeed

#

they're all default values except the one you assigned

dry cairn
#

just doesnt specify in the pic i think thts y i got confused

rich adder
#

tbh the one on the w3schools makes a bit more sense
especially with strings/names

dry cairn
#

so it told the array to put 5f into the array to be used later?

rich adder
#

now the array is follows

#

5f,0f,0f,0f,0f

dry cairn
#

oh so it started with 0f, 0f, 0f, 0f, 0f

#

an all it did was change 1

rich adder
#

yea unless you specify a value they all use default values

#

if you were to do GameObject, default value is null because reference types work different

dry cairn
#

so how would u change 5f, ?f, 0f, 0f, 0f

rich adder
#

from what you told me earlier

dry cairn
#

and my mind went blank this always happens let me try to reread

rich adder
#

if you changed value at index 0 to 5, what do you think the index of second element in array would be?

dry cairn
#

would it be 5?

rich adder
#

first element is at index0, how would second index be 5?

#

this is simple mathematics lol

dry cairn
#

then i think im misunderstanding im sorry

rich adder
dry cairn
#

ok so the float 5f got added earlier to make it 5f, 0f, 0,f 0f, 0f
and to answer u its 1

#

im confused where i got confused

rich adder
#

ok so what do you think the second index element is

dry cairn
#

i kinda dont wanna say cuz im not sure if its right but would it be 1?

#

or 6?

#

how did it become 1 if we are using 5s

rich adder
#

you asked about changing the value of the second float?

#

first you need the index of where it is stored

dry cairn
#

yea i fiqured it would be something like value[1] =5f

rich adder
#

right

#

arrays are 0 indexed, so to easily remember which one of the array you want going always -1

dry cairn
#

oh i think ik where i messed up

rich adder
#

You want the 4th element inside the array ? do 4-1

dry cairn
#

what would be the point of doing in the code if u can do it in the inspector

#

or wait are u pulling from the index in this case?

rich adder
#

inspector is only useful for Components, also you don't always want an array/list to be public or serialized

dry cairn
#

oh

rich adder
dry cairn
#

i kinda had them like tht so i could always see them so is tht a bad idea

rich adder
#

imagine you have a bunch of boxes, this makes up your array

#

in each box you can store stuff, but only the type of declared array

#

each box is numbered

#

so you know which thing goes where

dry cairn
#

thank u i think i have a "better" understanding

#

do u think id be able to message u if i have anymore questions bc u are VERY patient in explaining

rich adder
#

Also I'm around here often

dry cairn
#

ok good ive been using chat GPT to help but i was using it to try to help me get a character made buti could not get it to work at all

rich adder
#

the good stuff is pinned in this channel

dry cairn
#

like ive been researching how to put a character in a scene but i cant figure it out i used mixamo but when i added the character he t posed so i went back to get more anims so i couldnt figure out how to get them to work

rich adder
dry cairn
#

so dont think about doing anything till i get some more courses done on unity

eternal falconBOT
#

:teacher: Unity Learn ↗

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

rich adder
#

but I see you already used that so keep at it

dry cairn
#

im on like unit 2? i think

rich adder
#

are you doing essentials one?

dry cairn
#

i ve been having issues with remembering all the codes ive been told

rich adder
dry cairn
#

junior programmer is this not the rioght one

rich adder
dry cairn
#

which one should i do more to help me with the coding aspects to help me retain knowledge

#

i looked up this flash card thing but i dont know how to set it up

rich adder
#

the site i sent like w3schools are good for this

#

they also have some more traditional ones on the microsoft c# site

dry cairn
#

ill try the w3 schools one

rich adder
#

Like I said, when you learn for example array, You have to keep practicing it until it finally makes sense then move on to a new thing

dry cairn
#

i do tht before i continue on with my unity things an ill restart on unity as well to try to learn it again without the help of the video

rich adder
#

make array of strings, replace elements, count them, make new types of array etc

frank zodiac
#

Whats the best way to move a player for my 2d top down game?

#

is it transform.translate?

timber tide
#

depends if you want auto collisional stuff

rich adder
frank zodiac
#

i dont need collisions, maybe only trigger collisions

wintry quarry
timber tide
#

translate is probably fine then, but even then there's no interpolation done

frank zodiac
frank zodiac
wintry quarry
frank zodiac
timber tide
#

could look into character controller stuff. It's not rigidbody physics but gives you some tools for collisional purposes

rich adder
#

rigidbody2d

frank zodiac
frank zodiac
timber tide
#

oh, is there not? I've actually not done 2D beyond 2.5D ;p

#

I don't see why there isn't. It's just a raycasting controller.

frank zodiac
#

i see

#

ill consider it

#

thanks

timber tide
#

Ah, ok. So people questioning about that brackeys 2D video uses a custom made character controller which is what I was thinking of.

frank zodiac
rich adder
frank zodiac
#

no gliding

rich adder
#

both work, each with their pros and cons

timber tide
#

I usually do velocity for toggle, otherwise AddForce for continuous input

rich adder
#

velocity usually

frank zodiac
timber tide
#

docs say that velocity can clip your through colliders, but I've not experienced that

#

assuming you change it constantly

rich adder
#

I've read mixed things about directly setting velocity

#

never had issue myself with my usecases

frank zodiac
#

ill try both and see which ones more suitable

rich adder
#

addforce also has different modes

frank zodiac
timber tide
#

velocity is fine honestly. One problem is if you do have a fps spike, addvelocity will continue to move your guy without input until you set it to 0

#

so like I was saying, it's fine for a toggle

frank zodiac
#

should i use ForceMode2D.Force

timber tide
#

actually that issue is more related to how you do the input. I forget it's been a while.

frank zodiac
#

what does the error mean?

rich adder
eternal falconBOT
frank zodiac
rich adder
#

also don't use ? for unity components

frank zodiac
rich adder
cosmic dagger
rich adder
#

unity overrides it

frank zodiac
#

oh that solved the error

#

thank you lol

iron mango
#

i have a question, object pooling is better for performance than instantiate, but for that i have to instantiate them at start, and if i have a game with hundreds of projectiles on screen, do i just spawn thousands of them on start? and what if i change the fire rate? there won't be enough bullets available to spawn with a high fire rate

cosmic dagger
#

you need to spawn the amount needed at startup to fill the pool . . .

timber tide
#

yeah pretty much. Mem is cheap, spawn all you want when you can

#

you can always extend your pool too, but ideally just make a large pool

cosmic dagger
#

its best to spawn during startup since everything else is loading at that time . . .

#

having a dynamic pool is always an option, as well . . .

iron mango
#

but every "gun" has it's own pool right, not all have one

cosmic dagger
#

that depends on the projectiles. if they're the same, then they can share the same pool . . .

timber tide
#

Object Pools go hand in hand with dependency injection

iron mango
#

in my mind it just looks weird if every spaceship has 20 turrets, and every turret has a 200 inactive projectiles

#

and yes performance isn't bad

#

i tested it xD

timber tide
#

it should be 20 turrets that share from those 200 projectiles

cosmic dagger
#

again, if they are the same projectile, they can share the same pool . . .

iron mango
#

dynamic it is then ig

timber tide
#
[SerializeField] int initalPoolSize = 1000;
[SerializeField] int poolExtension = 50;
private Queue<Enemy> enemySystemPool = new();

public Enemy RequestEnemy(EnemySO enemySO, Vector3 pos, Quaternion rot)
{
    if (!enemySystemPool.TryDequeue(out Enemy enemy))
    {
        ExtendEnemyPool(poolExtension);
        enemy = enemySystemPool.Dequeue();
    }

    enemy.transform.SetPositionAndRotation(pos, rot);
    enemy.AssignUnit(enemySO);
    enemy.gameObject.SetActive(true);

    return enemy;
}

private void ExtendEnemyPool(int amount)
{
    for (int i = 0; i < amount; i++)
    {
        Enemy enemy = Instantiate(EnemyPrefab, Vector3.zero, Quaternion.identity, transform);
        enemy.gameObject.SetActive(false);
        enemySystemPool.Enqueue(enemy);
    }
}
#

that's basically what I do for every single pool

#

all enemies share a single prefab type here

iron mango
#

alright, but, if i spawn all those projectiles for the pool at start, so when i spawn a spaceship, won't that cause lag? because spawning one is during the round

timber tide
#

Right, well like I was saying with the same prefab type. If you expect any type of projectile, make a global projectile pool

#

spaceship spawns and now syphons projectiles from the pool

iron mango
#

where are the pools located then? (if i think about it i shouldn't use pooling 💀 )
if a ship is spawned that is from a mod, with all new projectile types-

timber tide
#

Singletons

#

ProjectileManager.Instance.GetProjectile(ProjectileSO)

#

then do some assignment method on that projectile

#
public void AssignAbility(AbilitySO abilitySO, Vector3 pos)
{
    this.abilitySO = abilitySO;
    
    transform.SetPositionAndRotation(pos, Quaternion.identity);

    //Reset state
    returnAbilityToPool = false;
    currentHitTarget = null;

    previousColliderHits.Clear();
    previousTargetHits.Clear();
}```
#

One of my projectile methods with DI

#

You can also do the assignment inside of the manager instead.

#

I choose the init/assign method way

iron mango
#

brain can't comprehend... shutting down atwhatcost

timber tide
#

Which part?

iron mango
#

(everything)
also, as i said, if a player is spawning a mod ship with mod projectiles, they are not it any pool yet, which will require me to instantiate them and will cause lag?

timber tide
#

You know what singletons are?

#

They are mono's that live on the scene and usually be living there from the start of that scene

iron mango
#

._.

timber tide
#

so the idea is to create one of these global monos and just cache all that data onto them for you to just grab as you please

iron mango
#

yeah that's what i don't understand

timber tide
iron mango
#

ok?

timber tide
#

They just sleeping there till I need them

iron mango
#

i know

timber tide
#

Well, reflect on the idea of a single prefab, dependency injection, and a singleton that provides monos globally to all objects which request it.

iron mango
#

forget it

#

i give up for now

timber tide
#

Start with a singleton that instantiates a bunch of prefabs at the start of your scene, and if you have any questions after that come ping me.

iron mango
#

what i think you mean is that i have empty prefabs and if a different type of projectile is needed the values are changed?

timber tide
#

the idea is all your projectiles have similar components. If you're using 2D you know these projectiles will always have spriterenders, if they are 3D they must have a model, and most importantly they have the Projectile script which drives them.

iron mango
#

well it's 3d, and if it's a different projectile it has a different script (laser, rocket, ...) they are very different

timber tide
#

So, if they all share these similarities, it shouldn't be hard to grab one of these prefabs and say, "hey rocket, you're now a lazer projectile"

iron mango
#

lol

#

i mean a laser flying in a straight line behaves differently than a homing missile with an explosion

#

i would need to change a script

timber tide
#

why can't you just flip a bool that says this lazer now homes?

iron mango
#

the game already is mod based

#

for custom ships/ projectiles (scripts)

timber tide
#

If it's already built up, I getcha. But in the future if you did want this modular single pool system they must be composite logic

#

but in your situation if the logic is greatly split, then yes you need to make a pool for each projectile type if you can't do dependency injection

#

and in this case you'd simply reset the state of your projectiles instead of injecting them with different data types

#

so, the same idea applies though that you should be making these pools as soon as you start the scene, even if you don't use them

iron mango
#

for each projectile in the game?

timber tide
#

each type of projectile

#

prefab

#

if you expect enemies to only have specific projectiles in a level, you can cut down on some pools like that

#

and instantiate new pools on level 2, ect

iron mango
timber tide
#

but everything a player can acquire, you want to make in a loading screen, or in a pause screen (maybe you got a select weapon screen?)

iron mango
#

that's the point it's a multiplayer game with mod support, and i don't put all projectiles of all mods + the vanilla ones in a list to pool at start

#

._.

timber tide
#

I'd profile it. Pooling isn't that expensive honestly, and there is ways to dynamically increase it like I've shown.

iron mango
#

yk what i will create the pool while shooting, so the first projectiles fired are instantiated, but put in a list to reuse

#

scared of lag if i spawn multiple

timber tide
#

if you start with a small data container and gradually increase it, that could be fine too. C# is pretty good at managing extending data types like that.

iron mango
#

kk

timber tide
#

Garbage collection is the bigger problem and just not destroying projectiles and recreating is already miles better

iron mango
#

can you help me with one more thing i am struggling with?

frank zodiac
#

what are the official c# unity naming conventions?

timber tide
#

same as c#

#

you'll see some inconsistencies from some methods, usually stuff that are properties

iron mango
# iron mango can you help me with one more thing i am struggling with?

the turrets shooting the projectiles,
i want them to rotate towards the enemy and i can't get it to rotate independent of the parent (if the turret is upside down or sideways)

Vector3 direction = target.position - transform.position;  
    direction.y = 0;
    turretBase.rotation = Quaternion.RotateTowards(turretBase.rotation, Quaternion.LookRotation(direction), horizontalRotationSpeed * Time.deltaTime);
``` example code fore one of the parts
frank zodiac
#

how do i add a {get; set} to an enum

timber tide
frank zodiac
timber tide
#

probably post the code and the error

frank zodiac
#

idk where to put it

timber tide
timber tide
#

unless you want to create a new enum then

public enum Enemy
{
   Enemy1,
   Enemy2,
}

private Enemy enemy { get; set; } ```
iron mango
timber tide
# frank zodiac ohhhhh i see

Oh actually you can't serialize auto properties like that you need to do

[field: SerializeField] Enemy enemy {get; set;}
lavish magnet
#

Hello all, trying to code popup text like this, but i am struggling with animations on making it smooth. Starts like this, and ends like this which works perfectly, however their is no lerping or smoothing. I tried to add it and it crashed


    public void MoveUp(float amount)
    {
        //If currently the newest (Still moving to original spot) and this is called again, our end position must be adusted
        if (isNewest)
            endPosition += Vector2.up * amount;

        rectTransform.anchoredPosition += Vector2.up * amount;

    }```

This function is on each text popup prefab, and when a new one spawns, it gets called on all of them in the scene. THe issue is  the `rectTransform.anchoredPosition += Vector2.up * amount, I want to lerp that but i'm not sure how without bugs.
timber tide
frank zodiac
#

wait why wont my enum show in my inspector?

iron mango
timber tide
#

Ah, maybe you're looking for localRotation then?

iron mango
timber tide
#

I'd say just use the parents rotation, but you're using rotate towards which takes a transform

iron mango
timber tide
#

You can do Quaternion.Lookat and use the parent's rotation to get a new rotation

timber tide
timber tide
#

I feel like you can just take the parent's rotation in place of the turret but rotate the turret using that rotation

iron mango
#

i am so confused

#

yk, i asked here, i asked on stack overflow, i asked chatgpt but i can't get it working i feel so dumb

timber tide
#

probably need something to see to go off of cause I'm not too sure of the requirements

iron mango
#

wait

violet glacier
#

Does it make sense that two scripts reference each other?

timber tide
#

Usually the proper way is that you have some delegate callbacks but that takes time

#

it's called bi-directional referencing, but honestly unless you're working with a lot of people it's not a problem

#

usually you see this with UI and slot (think inventory/UI) interactions as sometimes they need to communicate back and forth

iron mango
#

ok both models are children of the the turret object itself, one only rotateson x one only on y
which works but if i flip the turret upside down or sideways, ... they still rotate in the normal rotation and not upside down/sideways, ...

timber tide
#

I think I know what you mean but it's not something I've ran into enough of with doing rotations to really know at the top of my head.

#

I can only think that there may be some conditional logic on when it's flipped or not

violet glacier
timber tide
#

or some offset values when it is flipped

timber tide
iron mango
#

if the ship hull is not flat

#

well

fossil drum
#

What are you even trying to do? 🤔
Seems like an easy 2 step rotation right? 1 over the y axis then 1 over the x axis?

iron mango
#

._.

fossil drum
#

Whats your code to rotate? Probably EulerAngles right?

exotic hazel
#

Hello
So I am making a car game for an exhibition. I wanted to do if because of being so fast the car leaves the track. It gets teleported back to the start. So I gave the track a tag and used oncollisionenter to confirm that if the tag is not road change the position to the sytart. But nothing happened could someone tell how to do it.

Another thing I have an error in a script can it interfere with a function of some other script but on the same object? I have an error on the particle effect on the car can that intergere with the teleportation or anything in any way?

fossil drum
iron mango
fossil drum
# iron mango ah sorry the base is a child of the turret itself, like the barrel, those are ro...

Not what I was getting at.
If you have turretBase and turretBarrel the base needs to rotate on the flat axis and the barrel on the vertical axis.
But turretBase.rotation sets a global rotation, if I understand you correctly you want to let turretBarrel keep it's parent rotation from turretBase, but setting the .rotation is again the global rotation.
Isn't your whole thing solved by setting the .localRotation instead?

iron mango
#

wait how do i make it rotate on x only

timber tide
#

y = 0

#

or constrained to the previous rotation value

#

you can also chop on individual rotations using angle axis

iron mango
frank zodiac
#

what is this

#

how do i remove it

ivory bobcat
#

Looks like a break point

#

Click the red circle

frank zodiac
#

ok i just got rid of it

frank zodiac
ivory bobcat
#

Debugging purposes from the ide

frank zodiac
#

oh i see

late burrow
#

whats the shortcut for application.datapath but 1 folder earlier

twilit cliff
#

!code

eternal falconBOT
tepid horizon
#

I cant move without sprinting and this error keeps showing up.

twilit cliff
#

@tepid horizon Check in the hierarchy

#

@tepid horizon Share the script

tepid horizon
#

ok thank you i am now. but theres no reference point. attached to firsPersonController is my camera, Joint, and my character model

#

you able to find anything

twilit cliff
tepid horizon
#

425

#

NullReferenceException: Object reference not set to an instance of an object
FirstPersonController.FixedUpdate () (at Assets/Imports/ModularFirstPersonController/FirstPersonController/FirstPersonController.cs:425)

#

this is the whole error

twilit cliff
#

It's related to the Joint variable Transform, make sure it's assigned properly in the inspector

#

I'm a beginner as well but as far as I understood, it's trying to take the Transform reference of the Joint object which is not assigned properly

drowsy oriole
#

can someone help make me a script to fix this?

tepid horizon
drowsy oriole
#

2 problems

  1. the monster is supposed to look in the direction the nav mesh agent is
  2. Its not supposed to be in the floor
twilit cliff
tepid horizon
#

iits not there.

hexed terrace
tepid horizon
#

i dont have a line 425

hexed terrace
#

!vs

eternal falconBOT
#
Visual Studio guide

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

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

languid spire
tepid horizon
#

sprintBarCG.alpha -= 3 * Time.deltaTime;

languid spire
#

configure your IDE. It is required to receive help here

drowsy oriole
#

its a gtag fangame so nor the player or monster have feet

hexed terrace
#

ok, so extrapolate the meaning from what I said and what do you need to do....

tepid horizon
languid spire
tepid horizon
drowsy oriole
languid spire
hexed terrace
hexed terrace
#

As you haven't shown it, and like I already said... I ASSUME it's in the middle of the monster, which is why the monster is in the floor.

drowsy oriole
#

where do I find it

hexed terrace
#

do you mean - "What is the pivot?"

drowsy oriole
#

i just started unity

hexed terrace
#

ok.

#

Do you mean - "What is the pivot?"

drowsy oriole
#

yes

dry cairn
#

can someone give me a hand its not telling me Game Over in the console window

hexed terrace
hexed terrace
dry cairn
#

was gonna copy an paste didnt know if it was too big or not

hexed terrace
#

!code

eternal falconBOT
drowsy oriole
#

ok you are right it is in the middle of the player how do I move it down

dry cairn
languid spire
hexed terrace
hexed terrace
#

or if you modeled this yourself, go back to your 3d prog and do it properly in there

drowsy oriole
#

and then what

#

Carwash

hexed terrace
#

and then what what?

drowsy oriole
#

it still dont move with the player

#

and still goes in the ground

hexed terrace
#

of course this doesn't affect that

#

you have to point the Nav stuff to the parent now

drowsy oriole
#

it still goes in the flor

hexed terrace
drowsy oriole
hexed terrace
#

... see how your pivot is STILL in the middle of the monster

#

select the children (Armature + Cube + anything else) and move them up until they're in a good position

#

at this point, i really think you should go back and !learn the basics of Unity 👇

eternal falconBOT
#

:teacher: Unity Learn ↗

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

drowsy oriole
#

no im good

#

just one more thing

#

how do I fix the rotation

#

i fixed the pivot btw

hexed terrace
#

by telling it where to rotate to in your !code

eternal falconBOT
drowsy oriole
#

I am not a good coder

hexed terrace
#

So? What difference does that make? You get good by keep doing and learning

#

But I've gotta go now, someone else will have to pick that up .. while you wait, try fixing it yourself.

google things like :
unity how to rotate an object
unity how to make an object look at an other
etc

late burrow
#

or ask gpt

stuck palm
#

Can structs inherit each other?

teal viper
#

Structs can only implement interfaces afaik