#💻┃code-beginner
1 messages · Page 372 of 1
Ask them what dependencies you need to install
ok thanks
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
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
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
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```
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
because you're completely overwriting the velocity every FixedUpdate
oh how do i fix tht
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
how do i debug im VERY new
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
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
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
thank u
How can i make a unity slidfer follow this trail? I want the ball to slide from the ends
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.
Nope Cant do that
Nope, not interactable*
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
No, no reason to do that
No slider component
Sliders are for interaction
And they're hard coded to be straight
You'll need to make your own thing
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
how do i do that 😭
You need a $ in front of it
I see, and why does that work
@rich adder thanks sm
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
Use the curly braces with the cases to isolate the statements
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.
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
ill try that thanks
That seemed to have done it
Ah i just implemented the code but the second switch uses specialToken instead of standardToken
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
What? I have no idea what these words mean.
Also what does this have to do with code?
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
disable the renderers for objects that shouldn't be rendered
Or use the Near Clipping Plane distance on the camera to exclude them
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
its instantiating many balls, what alternative method i can use
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);
}
}```
You could probably evaluate when the touch began (phases) and combine it with a cool down timer or something
problem is with instantiating, its spawning multiple balls even with given delay, will it fix this?
Did you look at the link I shared?
yes i did
The multiple balls is happening because of this actually
Becasue you're starting 8 bajillion Invokes
that all set CanPlace = true
so this code suggestion alone should fix it
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.
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;
}
}
}
Because you have a recursive while loop
If flashlight.enabled is false it will just restart the while loop infinitely
To fix it, add a delay in an else statement
IEnumerator batteryDrain()
{ while (true)
{
if(bool that is false){}
}
}
oh ok, thanks
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
thanks
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
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;
}
}
}
[field: Serialize] or [SerializeField]?
[field: Serialize] throws an error so [SerializeField]
Use [field: SerializeField] for properties
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
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?
is there any way to close quickly a lot of scripts in visual studio?
middle mouse button click on a tab
and to close all of them except the one im in
or all
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
Thanks ❤️
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
AI and pathfinding are not the same thing. But sure, both of those will fix your pathfinding problems.
what would you say ai would be in that context
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.
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
That's a good idea, fix the problem in smaller pieces.
did you change the surface arc
i left it as default
liek i can jump through from the bottom and land at the top but the sides are making me collide
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
okay
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);
}
}```
is the input actually changing? or is the object just moving
ohh thank you so much man
check your input manager
leaning something on your keyboard?
The input is changing. The inputs are set to zero before I hit play
Everything in the input manager is default
No lol
if you unplug the keyboard does it stop
these are set in the inspector? i cant see why this would matter but maybe try making the variables private see if theres a difference
It does not stop
Try restarting your computer?
Setting them to private didn't change anything
Guess I'll give that a try
with the new input system, at least, I've had problems where I need to reconnect a controller to fix a ghost input
specifically my wireless xbox controller on my macbook
Restarting fixed it
Wonder if it was some ghost input from one of my many custom flight sim controllers
Can I have an object that only exists in the code have a Collider2D?
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
Okay, thanks
are you trying to do something in particular?
If, for some reason, you're creating a GameObject from zero via code, you can just call AddComponent on it
is there a reason for why the _defaultPosition goes so high even though in editor the objects transform is this?
Is this GO a child of any parent GO?
The transform you see in the inspector is local position. You're logging world position
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.
Is it possible this is being called without having the InputSys scene loaded? Perhaps if it were called twice?
(note that it doesn't run "on a new thread")
I can see it being loaded on the hierarchy in play mode
Can you help explain that, I thought since it runs in the background it runs on a new thread 😛
I'd sanity check by making sure you don't call WaitForUnloading anywhere else
shift-f12 while the name is selected
think of how a coroutine isn't threaded -- it just runs for a little while each frame
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 )
Well I found this on forum xD
oh, yes, you were trying to do that
Yup haha
"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"
Well I have multiple scenes loaded
i've loaded and unloaded a scene without loading any other scenes in-between
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
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"
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
You will need a reference to this component.
I did but it didn't work
what class did you declare that method in?
Why not just return birdIsAlive;? No need for an extra if statement here
BirdScript
Oh waittt now I understand
Okay, so whoever wants to ask if the bird is alive needs a BirdScript
I have to write BirdScript rather than LogicScript
Thanks
ah, yes, you used the wrong type
it tried to get a LogicScript component from the object tagged "Bird"
so it gave you nothing
Why is this if statemenet returning error
It says this
How can I compare teh value?
the method returns a bool, which you can compare to true
It is now working, thanks man 🙂
I declared a bool variable rather than the method itseld
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
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
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?
Welcome to the A* Pathfinding Project Documentation.
i am fairly sure its a legit thing
if theres no issues with turning that off then its fine
it'd be this setting, found in the "Other Settings" section of the Player settings
thanks i couldnt find it
{
SceneManager.LoadScene(sceneId);
}```
Why is this not working? i tried with scene name aswell
oh tysm!
welcome
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
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
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
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
uhmmm i think the issue is that it says
To add a scene to the build settings use the menu File->Build Settings...```
even tho its in there
There is no such thing as "Prologue Class". There is "PrologueClass"
ooooooh
its case sensitive, mb, cuz if i use caps unity automatically puts a space in there with inspector
tysm! it all works now!
Surely it is
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.
by inventory I mean a class that holds the Item list in it
The Item part just confuses me
What's the difference between these both variants?
There may be no difference. Thats why I am confused.
How do you want to save the inventory?
Like serialize the contents and the slots somehow and load them back in.
You want them to stay persistent when loading the game again?
Yes.
Yes I have the data handler already for that It just does not deserialize the scriptable objects
prefer saving just items and than populate inventory
How can I do that? My brain is like a soup at the moment.
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
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
Yes, serializing the objects on runtime is going to set them back to their initial values when the game ends
SO behave slightly different when game is build in comparison to Editor runtime.
So I have to keep updating them?
Not all the items have to be saved separately
No, you cannot achieve this by simply serializing them in the Inspector. That's why we're talking about json now
i think at this point its about data virtualization...
u need to define structare of save data that will let you reconstruct objects again
Well we can keep the player data in the persistentdatapath. And when scene loads it deserializes (json) then it all works.
You would usually have a class, which contains a List of your items. The class can be casted to json and back
That class is inventory then?
Yes, it would usually be
honestly don't know common approach, but for me saving system is separate thing
So I make an Inventory class Which holds the Item(SO) list
and also the inventory slots right?
You then get the List of Items from your saved json, which you then enumerate through to add them to your Inventory once more
the inventory slots hold the inventory items. Inventory items are scriptable objects fed into the InventoryItem.
Assuming the inventory slots are the UIs, yes
Yeah they are just images.
Then this should be a great approach
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?
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?
- Have a
static class, which contains theclasswith aListof yourItemScriptableObjects - Add the
Itemsto theclass' list using thestatic class' methods - When you exit the game (or a scene), save the items to a
jsonfile - When you enter the game, get the items from the
jsonfile, and enumerate through them to add them to yourInventoryonce more in the specified order
either use addresables or put Mateterial in Reources folder and than u can make static helper method to retrive that at any point
o one class in another?
Right
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
exatly! keep single resposibility! create class for handling persistence of data, and let inventory just be inventory...
Okay I will try. Never nested classes like this so im a bit confused 😄
I also like to make it a public static in a static class
I wonder whether you can call that nesting
its not nesting... its basic composition
I see
It's the same way you would use any other class in your script
Like... a Coroutine?
netsing would be to define class in a class... with have its use cases... but not here xD
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
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
Hm okay. I think i got it
So uh the utility class in my case is for writing and reading jsons
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
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.
Ideally you would have some class which handles the actual writing and loading, so you arent repeating logic for every single class that wants to save data. Then this inventory uses save system
No, I would do it in a non-static class, as it would be easier with the various paths
man you getting so much helping love xD
well there is more than 3-4 ways do it it so sure it will be confusing xD
Well, we've been talking about a single one
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
Ill do dis
I'm not saying that the approach I have mentioned is the only one, but that's what I would use.
- A
staticutility class for adding theItemsto yourclass InventoryData - A
non-staticclass to handle the serialization and deserialization ofjsons. Make sure to access the paths usingApplication.dataPath
thing about serialization in unity is that it is relevant only in moment of building... game after build will always return to its initial state
Changes to your SO does not persist in a build, so its something that doesnt really make sense to save. It's meant to be just a data container, some read only stuff.
Theres nothing special for reading the data, you just reference the asset and it's all available
how does a singleton actually work? How can I reference a static class as if it was a normal class?
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
What do you mean by referencing a static class as if it was a normal one?
Singleton is not a static class. It is a static reference to an instance of a class
ahh
you create normal non static class and do not make public constructor... also you have public static acces field to instance of self. in case of monobehaviors there is bit more twiks to it
Yes thats where I got confused. How can I get the data of my Item from Json because I get the information on my Inventory Items from SO's.
If you look online at Newtonsoft, there will be tons of examples how to read from file
It handles all of it for u
The difficult part here is recording which scriptable object assets you were using
wait i think i got you... do your SO even change state or they just have for example image (that will never change) and thats it?
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
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]
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
https://gdl.space/alapezutic.cpp
This is the converter that I use. Identifiable is an abstract ScriptableObject-derived class. When the game starts, I read all of the Identifiable assets into a giant dictionary. I can then use that dictionary to look up the object by its ID.
https://bronsonzgeb.com/index.php/2021/09/11/the-scriptable-object-asset-registry-pattern/
It's this pattern.
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.
using a converter means that I don't have to do any extra work -- Json.NET directly gives me the objects
You could also just serialize the IDs manually and then look them up yourself
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
- Your error is on line 18 of
CollisionDetectionbut there's nothing there - What is
enemyhealthinCollisionDetection
I can hold Player data which is just an ID and rotation and position. I just could not figure out how to do it in inventory.
It is the enemyhealth value
you want to get SO's by ids and ppulate invetory with them at given index
sorry, i typed the line after the pastebin log
There's nothing named that in your CollisionDetection script as you shared it, but since your error is on a line that isn't in there anyway, share the current code
Okay so what is enemyhealth
Make a list of all of your inventory items. Give each one of them a unique ID. Save that ID to serialize. Deserialize by reading the ID and then looking the item up in the list.
simple... you never defined this variable
sorry could you elaborate
Do I make a list of Inventory Items or the Item SO? because like I feed SO's into inventory items.
You have literally nothing named enemyhealth in this script
you're trying to use a variable you have never made
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
The scriptable object assets that you need to be able to find later.
I'm trying to access the public variable
there no field, nor variable with that signature
This is a completely different script and has nothing to do with the error
ahh ok, how do I access the variable in enemyHealth script in this script?
Ah okay. Understood. And the InventoryItem(the actual item that is in the slot)? Do I make a list of that too?
Which EnemyHealth instance are you trying to access
the variable consisting of the enemyHealth
public float enemyhealth; in the pastebin
That doesn't really answer my question
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
the float that holds the value for health
that's not what I asked
first of all i feel like you should either set up your vs code properly or just use actual IDE than you would see that there is no enemyHelth Symbol defined
I'm asking which EnemyHealth (component) you want to get the float enemyhealth from
ahhh
from this slider
So then you need to reference that object.
https://unity.huh.how/references
i've currently set it up so that when Z is pressed healt goes down
*as seen in the mentioned linked scripts
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 :/
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.
decrease enemyhealth when collision is detected?
you can look into OnCollisionEnter, then compare the tag from there
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);
external token not provided
which line is this from?
looks like the last line, could you check if accessToken is null
huh
It is null
Shouldn't it be populated from SignInAnonymouslyAsync?
thanks
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
public async void SignIn()
{
try
{
var accessToken = PlayerAccountService.Instance.AccessToken;
await LinkWithUnityAsync(accessToken);
}
catch(Exception ex)
{
Debug.LogError(ex.ToString());
}
}
It is in one.
Did you read the thing I sent about how to reference an object
Sorry i'm stupid i've just realised
tysm for sticking with me and my annoying self
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
I asked him about creating an object. Is he yapping?
ofc this is plain cs, not unity one
why does PrizeClick not show up in the On Click() menu?
because it has two parameters
UnityEvent inspector only supports one parameter
serialize the parameter separately
Is he "yapping"? That is indeed a struct with a constructor and making a new instance of it....
public int price;
public GameObject delete;
public void PressButton() {
PrizeClick(price, delete);
}``` @spare gate
unsure how to create an object with variables of different type
so i should call a seperate function inside the pressButton function?
in js that's simple as hell, dunno about cs
simple in C# too
They're called classes
(or structs, but that can wait)
Can you be specific about what exactly you're doing?
Because you just showed code that does create a new struct object...
If you want to make that object a class, write the word class instead of struct...
If you mean a GAME object, then that is a little different. You likely would want to use Instantiate on a prefab reference
just tkink its ts and dont do functional stuff xD
Hi. What is the best way to make HP recount? Which will be secured and easy?
What does recount mean here, and what does secured mean here?
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
takeDamage
That does not answer either question
when someone hit player or enemy
But yeah, making a TakeDamage method is very easy
Something more comfortable to use than like 5 variables with the same prefix to differenciate
is what I mean
So like a dashStats struct or class or scriptable object?
dashBar.progress.target or dashBar.progress.current feels better than combining all
Ok. It is good way to make public takeDamage() method?
just a dash or dashBar, yeah. I need different value types and an unspecified ammount of them
define struct and add serializable attribute... or even SO
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
u know js support object like way with constructor?
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
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.
Well, how would you do damage otherwise? ;p
objects in static languages are... static(in terms of of structure). c# supports dynamic type but its not recomanded unless u really know what are you doing and ussly there are better options
you make classes/structs for each of those maps
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
what does "load" mean here?
i am thinking about how i'd translate this
load is field with : {
progress: 0,
target: 60
}, object
well
yes, i can tell
but what does it mean?
I can't really understand what the design intent is here
dynamic languages support something like Anonymus objects... you dont need to define structure like class u can just create object on fly
i am (painfully) familiar with how that works, yes
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
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
you mean exactly this case not in general? xD sorry if so xD
Usually these type of methods where you've some object interacting with another you will usually have to have a way to access those methods. So yes, you'd have some public accessor to get/set the other object's data.
sorry bro, i am getting slow at late houers xD now when i read it back if feel awkwardly annoying xD
The alternative is to have some manager in between that will only be able to access these objects, which you would communicate to instead. But, that's not always needed.
Thanks
is it more expensive referencing another class's variable as opposed to your own variables?
They want to know the purpose of that specific code so it can be translated properly
no
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
yee i got it now, makes me feel little stupid, but also realize that I may should go to sleep xD
Ah no worries. All good
okay thansk
https://paste.ofcode.org/3M7zPxeEEnWVugvmnQTXXn
@hollow dawn
i see where ur conditional is..
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 ^
Because that property is a ClampedFloatParameter - as the error is implying
so you can't put a float in it
so what do I do
bro my crouch input was in another script lol
0.4f
To make it a float, instead of double
you probably want something like vignette.intensity.value = whatever;
just like the other one right above it you have
worked, thanks mate
somehow it's locked at 1
why is it locked at one
how would i fill up a bar based on a timer in a coroutine?
depends on how you want it to fill
smoothly? Stuttery?
linearly? Some kind of easing function?
depending on some other variable?
linearly
just a while loop, with a yield return null, and proper use of Lerp
oh okay, thanks!
could i get some help with this
https://paste.ofcode.org/Sx76X9jqU4vEVTBkT4g82t
i dont know how to make force public
Assets/scripts/movement.cs(49,45): error CS0103: The name 'force' does not exist in the current context
Declare it in the class, not the method
You can SET it in the method
So, just remove float right before force
ok
And add public float force up top
what about something like this
public void ApplyForce(qForce)
Did you ONLY remove the word float from that line?
yes
Not sure the context here, so I can't say
ok but do you know how to fix this
Assets/scripts/movement.cs(33,34): error CS1001: Identifier expected
nvm
i figured it out
Is your ide configured?
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
Storing the state in something that is added to the DontDestroyOnLoad scene.
An ItemManager seems reasonable
if you dont want it to come back between runtimes you'll also need a save file
yes I gotta relearn that, when I tried to do it with something else(saving a simple name as a string in a JSON file) i failed
It can be tricky
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
sounds good. how does saving things to a file work in the editor? will pressing play and stop and play again persist if the save data code is run?
is there a function that activates once the object the script is on is activated?
OnEnable
https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnEnable.html, but i would search: "onenable unity"; there are some video links that tell you the difference between Awake, Start, and OnEnable . . .
works thx
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
depends how much realism you want
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
not a lot actually, the game is rather cartoonish
fishhook and the fish can just be some trigger event using colliders. The boat mechanic can be as simple as adding velocity in the direction of your input
if you want some more realism, only allow velocity somewhere in the forward direction
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
thank you mao! I will look into that
Thats some good advice thank you :) I already have an idea of what I want but i'm really bad at coding and i'm trying my best to figure things out
it's in pixel art and most of the art is done
https://docs.unity3d.com/ScriptReference/Collider.OnTriggerEnter.html
For the hook.
https://docs.unity3d.com/ScriptReference/Rigidbody-velocity.html (addForce is fine too, but velocity works)
For the boat (if you want to use rigidbodies)
saved it! <3
never heard of unity documentation
will look into that as well
you live a dangerous life
Once I get into it there's no coming back? 
I meant you've not been using documentation
it's basically a cheat sheet
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
why does my fill bar not fill up linearly rather it's fill amount just jumps to a fixed value when i press play?
https://hatebin.com/yiffppqzho
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...
The while loop will complete in a single frame because you don't yield inside of it
just ignore it, restart Unity if you havent
That's an editor error, usually caused by having the animator window open
Is it just having it open in general or caused by a specific situation?
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
Understood, I shall ignore the blinking red light 🫡

restarting unity did remove it from poping up for now
The animator is easily startled. It will soon be back and in greater numbers
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?
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
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
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?
sorry, i meant pressing play and stop reloads the editor and would be similar to closing the game in a build. the question was asking if it still would save the data to a file that is specific to the editor
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
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?
Make sure Toggle is only running once
Yes, with GIMP or Photoshop
not a code question
so theres no way of me doing it in unity?
There's a way to do everything
I did, I had a Debug.Log() in toggle and it was getting called only once, I'll rerun that just to make 100% sure.
but with your vague description, sounds like photoshop is your best bet.
Motion time was useless. Changing the Speed multiplier was the most effective, will have to tune it tho
Anyway doesn't sound like a #💻┃code-beginner question anyway
yeap, Toggle() is getting called only once :/
Use the debugger
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
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
Convert to normalized time and pass that in
Thats what I ended up trying but it only played 1 out of the 5 sprites I had.
are you actually converting it, or just passing the real time to normalized time?
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
can you show your weapon script?
also can you not flood chat or at least color your code? !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
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);
}
}
"Fire" and "fire" are two different things
it IS case sensitive
take another look
oh shit thank you
np
I'll have to pop up my code tomorrow but If I remember right I am grabbing the length of what it was. Dividing that by my time
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
you're using the index 0 in the array and assigning it a value of 5, arrays start with index of 0
so does that mean it wont start at 0 anymore an itll start at 5?
no, what makes you come up with that conclusion
this is an array with 5 float numbers
i have no idea im still kinda confused with arrays
did you look at the link I've sent?
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);
pretty much
ah ok thank u for some reason i had so much trouble with tht
yeah tricky at first but they are powerful, keep practicing using them eventually they will be easy to deal with
so the array in the pic has 5 different floating numbers
just doesnt specify in the pic i think thts y i got confused
tbh the one on the w3schools makes a bit more sense
especially with strings/names
so it told the array to put 5f into the array to be used later?
it just replaced the first value of 0f with 5f
now the array is follows
5f,0f,0f,0f,0f
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
so how would u change 5f, ?f, 0f, 0f, 0f
well how would you access the second element of array
from what you told me earlier
and my mind went blank this always happens let me try to reread
if you changed value at index 0 to 5, what do you think the index of second element in array would be?
would it be 5?
first element is at index0, how would second index be 5?
this is simple mathematics lol
then i think im misunderstanding im sorry
whats 0 + 1
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
ok so what do you think the second index element is
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
you asked about changing the value of the second float?
first you need the index of where it is stored
yea i fiqured it would be something like value[1] =5f
right
arrays are 0 indexed, so to easily remember which one of the array you want going always -1
oh i think ik where i messed up
You want the 4th element inside the array ? do 4-1
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?
inspector is only useful for Components, also you don't always want an array/list to be public or serialized
oh
the index is like "position" it stored at
i kinda had them like tht so i could always see them so is tht a bad idea
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
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
You could just post your question, there are lots of helpful patient people here not a worry
Also I'm around here often
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
honestly it will be more harmful than helpful, best you do actually structured courses that step you through novice to advanced
the good stuff is pinned in this channel
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
!learn has all sorts of videos including how to use animator and humanoid rigs
so dont think about doing anything till i get some more courses done on unity
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
but I see you already used that so keep at it
im on like unit 2? i think
are you doing essentials one?
i ve been having issues with remembering all the codes ive been told
when you learn something new, you have to practice it and do examples yourself until "it clicks"
dont move forward until it does
junior programmer is this not the rioght one
its good yeah keep at it, they have more there
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
do a little bit of that and a little bit of basic c# practice
the site i sent like w3schools are good for this
they also have some more traditional ones on the microsoft c# site
ill try the w3 schools one
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
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
make array of strings, replace elements, count them, make new types of array etc
Whats the best way to move a player for my 2d top down game?
is it transform.translate?
depends if you want auto collisional stuff
not if you want collisions to work right away
i dont need collisions, maybe only trigger collisions
Nobody knows anything about your game so...
translate is probably fine then, but even then there's no interpolation done
its an rpg game with minimal combat focusing on story
well what would be the best way IF i was using collisions?
Ok but how should movement work? For example classic Pokemon games used frid based movement
not grid based, just regular movement
could look into character controller stuff. It's not rigidbody physics but gives you some tools for collisional purposes
rigidbody2d
okay thanks
theres no charactercontroller2d though
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.
Ah, ok. So people questioning about that brackeys 2D video uses a custom made character controller which is what I was thinking of.
.AddForce() or .velocity?
depends what you're going for
both work, each with their pros and cons
I usually do velocity for toggle, otherwise AddForce for continuous input
velocity usually
what are the pros and cons?
docs say that velocity can clip your through colliders, but I've not experienced that
assuming you change it constantly
hmmm interesting
I've read mixed things about directly setting velocity
never had issue myself with my usecases
ill try both and see which ones more suitable
addforce also has different modes
yeah im aware
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
should i use ForceMode2D.Force
oh that might be an issue
actually that issue is more related to how you do the input. I forget it's been a while.
can you show the full function !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
also don't use ? for unity components
why?
doesn't work on unity components
yeah, don't do that . . .
unity overrides it
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
you need to spawn the amount needed at startup to fill the pool . . .
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
its best to spawn during startup since everything else is loading at that time . . .
having a dynamic pool is always an option, as well . . .
but every "gun" has it's own pool right, not all have one
that depends on the projectiles. if they're the same, then they can share the same pool . . .
Object Pools go hand in hand with dependency injection
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
it should be 20 turrets that share from those 200 projectiles
you have to determine the max/average amount of bullets each object will have on screen . . .
again, if they are the same projectile, they can share the same pool . . .
yeah i just thought what if the player changes the firerate of one to be so fast it drains the pool (lol)
dynamic it is then ig
[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
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
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
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-
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
brain can't comprehend... shutting down 
Which part?
(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?
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
._.
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
yeah that's what i don't understand
ok?
They just sleeping there till I need them
i know
Well, reflect on the idea of a single prefab, dependency injection, and a singleton that provides monos globally to all objects which request it.
uh what
forget it
i give up for now
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.
what i think you mean is that i have empty prefabs and if a different type of projectile is needed the values are changed?
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.
well it's 3d, and if it's a different projectile it has a different script (laser, rocket, ...) they are very different
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"
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
why can't you just flip a bool that says this lazer now homes?
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
for each projectile in the game?
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
uh
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?)
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
._.
I'd profile it. Pooling isn't that expensive honestly, and there is ways to dynamically increase it like I've shown.
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
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.
kk
Garbage collection is the bigger problem and just not destroying projectiles and recreating is already miles better
can you help me with one more thing i am struggling with?
what are the official c# unity naming conventions?
same as c#
you'll see some inconsistencies from some methods, usually stuff that are properties
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
how do i add a {get; set} to an enum
Same as any other auto-property field
when i put it in it gives me an error
probably post the code and the error
So is the problem just that because of the parent child relationship that it's being rotated by the parent
private Enemy enemy { get; set; }
unless you want to create a new enum then
public enum Enemy
{
Enemy1,
Enemy2,
}
private Enemy enemy { get; set; } ```
ohhhhh i see
thank you
ah sorry i meant dependent of the parent rotation not independent xd
so, the parent (turret itself) for example is rotated 180 degrees, and the child (the turret i rotate with code) always looks at the target the same way, but i want it to be dependent of the parents rotation to also be upside down (why is this so hard to explain wtf)
Oh actually you can't serialize auto properties like that you need to do
[field: SerializeField] Enemy enemy {get; set;}
oh yeah i forgot abt that
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.
so you don't want the child to rotate with the parent when the parent rotates. You can look into RotationConstraint class and make its rotation based on a stationary gameobject (like gamemanager) or just dont child it to the parent and instead make it a sibling relationship inside of a container, OR just reduct the rotation from the parent.
wait why wont my enum show in my inspector?
no, i want it to rotate with the parent raaaah idk how to explain
Ah, maybe you're looking for localRotation then?
that doesn't work tho, i tried
I'd say just use the parents rotation, but you're using rotate towards which takes a transform
and it has multiple parts, one only rotating on x one only on y
You can do Quaternion.Lookat and use the parent's rotation to get a new rotation
Oh wait you are using Quaternion's Rotate towards uh
I feel like you can just take the parent's rotation in place of the turret but rotate the turret using that rotation
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
probably need something to see to go off of cause I'm not too sure of the requirements
wait
Does it make sense that two scripts reference each other?
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
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, ...
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
Thanks, this is similar to mine
A slot with
- script 1: information (item name, picture, etc)
- script 2: event system (handle clicks)
should I just put these two together in one script instead?
or some offset values when it is flipped
Slot stuff I have both event system logic and the data together
i used a bool to set if it's upside down or not, but that's not really a solution
if the ship hull is not flat
well
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?
yes i know but i can't get it working that's why i feel so dumb
._.
Whats your code to rotate? Probably EulerAngles right?
here
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?
Hmm, is this the child code or the base code?
ah sorry the base is a child of the turret itself, like the barrel, those are rotated through code, the turret itself is what for example rotate upside down to stick on a spaceship
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?
wait how do i make it rotate on x only
y = 0
or constrained to the previous rotation value
you can also chop on individual rotations using angle axis
y is what i set to 0 for rotating on y only xd
ok i just got rid of it
whats it for?
Debugging purposes from the ide
oh i see
whats the shortcut for application.datapath but 1 folder earlier
Just check the docs for Application https://docs.unity3d.com/ScriptReference/Application.html
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
You haven't assigned the specific object to the FirstPersonController Script, click on the object that is attached to FirstPersonController and make sure the reference object is assigned
@tepid horizon Check in the hierarchy
@tepid horizon Share the script
ok thank you i am now. but theres no reference point. attached to firsPersonController is my camera, Joint, and my character model
cc:
you able to find anything
Does the error says 425 or 42:5?
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
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
its weird cause i can move but i need to either sprint or jump and then it works for a second then just stops so i dont know
2 problems
- the monster is supposed to look in the direction the nav mesh agent is
- Its not supposed to be in the floor
Not to worry, someone here who's better will help you out, please do wait for response and hope it gets fixed soon, I also came here to post the issue I'm facing...
Show line 425 of the script
For some reason you're in the edit collider mode, so I'm assuming your pivot is in the middle of the enemy. The nav stuff sets the position of the transform using the pivot, so you need to put the the monsters pivot at the same Y pos as the feet
i dont have a line 425
sure you do, line counts don't skip over numbers.. it's just hidden, you can expand and see line 425.
HOWEVER you need to configure your VS 👇
!vs
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)
because you have the code collapsed
sprintBarCG.alpha -= 3 * Time.deltaTime;
there is no feet
configure your IDE. It is required to receive help here
its a gtag fangame so nor the player or monster have feet
ok, so extrapolate the meaning from what I said and what do you need to do....
Sorry where you talking to me?
yes
it must be outdated i definetly had it configured
its not working but that isn't the collider for the monster, that's the jump scare collider
well do it again, because it most certainly is not configured now
I hate having to keep spelling things out ...
so I'm assuming your pivot is in the middle of the enemy. The nav stuff sets the position of the transform using the pivot, so you need to put the the monsters pivot at the same Y pos as the feet
Move the pivot of your monster so that it is located where you want the monster to touch the floor.
WHERE IS THE PIVOT
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.
where do I find it
do you mean - "What is the pivot?"
i just started unity
yes
can someone give me a hand its not telling me Game Over in the console window
The red/ green/ blue axis gizmo that appears when you click on an object
Why would you highlight the text like that making it harder to read ? 🤣
was gonna copy an paste didnt know if it was too big or not
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
ok you are right it is in the middle of the player how do I move it down
debug your collision to make sure it is even being called and what is calling it
carwash
Create an empty game object, put the monster as a child and move the monster so that when you click on the parent it's pivot is where you need it to be on the child
or if you modeled this yourself, go back to your 3d prog and do it properly in there
and then what what?
of course this doesn't affect that
you have to point the Nav stuff to the parent now
it still goes in the flor
this is a code channel, move to #🧰┃ui-toolkit
... 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 👇
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
no im good
just one more thing
how do I fix the rotation
i fixed the pivot btw
by telling it where to rotate to in your !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I am not a good coder
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
or ask gpt
Can structs inherit each other?
No
Structs can only implement interfaces afaik