#💻┃code-beginner
1 messages · Page 371 of 1
Are you trying to crisscross a Scene Object on a File asset?
Why is Update not yellow?
unity messages might not by default. does it matter?
nah just wondering
guess its just the way your IDE work
there must be some difference, might be nice to know
I think its unity messages (Update, Start, OnCollisionEnter etc.) which doesn't get colored in Visual Studio but your own methods do
Unity specific methods (Awake, Update, OnCollissionEnter etc) are written in blue to indicate they are handled by Unity and should not be invoked by the game.
Also, be careful with async void methods. Not handling async code can lead to unhandled exceptions and undefined behavior in your code.
hey! so I have this peculiar problem where I'm using Transform.LookAt to orbit these projectiles around the enemy, but the weird part is that the projectiles are getting more and more distant every second
imma send code in a sec
I do
transform.LookAt(_orbitPoint);
transform.forward = -transform.right;```
It's nothing to do with the lookat
to rotate the object around the point
how would you tell?
because lookat does roation, not movement
the velocity is a constant
you have a rigidbody on the projectiles.. you can see they have velocity in all axis..
and I just make the projectile move in the direction its facing
share all 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.
void FixedUpdate()
{
time += Time.deltaTime;
if(time < _orbitAfterSeconds || _orbitAfterSeconds <= -1){
Vector3 angleVelocity = new(0f, _baseModifier * directionOverTime.Evaluate(time), 0f);
Quaternion deltaRotation = Quaternion.Euler(angleVelocity * Time.deltaTime);
rb.MoveRotation(deltaRotation * rb.rotation);
} else {
transform.LookAt(_orbitPoint);
transform.forward = -transform.right;
}
}```
the upper part is responsible for other stuff
basically for the projectiles to go out
and for the velocity I do rb.velocity = transform.forward * moveSpeed;
where
in a projectile handler script
I can send you the whole script but 90% of it is just hit detection
and enable/disable events
I use an animationcurve to set thespeed, but in this case the velocity is a constant
I'm confused, if you are setting velocity why are you surprised that the position is changing?
thats not the issue
'tis
the problem is that its straying further and further away
it still has velocity for it to move farther and farther away
'but the weird part is that the projectiles are getting more and more distant every second'
that is position changing caused by velocity
yeah, but they shouldnt be getting more and more distant if they're meant to orbit
but that is not what you are doing
but they still have velocity in the direction to move them away
what's a better way of creating orbiting then?
where the projectiles form a circle that doesn't change it's radius?
you need to set the direction of your velocity along the arc of the orbit
and how do I get the arc of the orbit?
calculate it, it could be as simple as a circle
my idea is that I don't change the direction of the velocity, I change the direction of the projectile, if that makes sense
I only apply velocity on the Z axis
I just change the Z axis
I don't apply velocity on the X axis as an example
the projectiles always move forward
unfortunately, this IS rocket science
I know
but I don't want to calculate some relative gravity stuff
also im afraid to see what happens if my enemy moves
I really dont think that the laws of physics care very much for what you do or do not want
yeaah thought so
some of them speed up, others slow down
how could I calculate the....
I actually semi-know how to calculate the circle
I just don't know how to implement it
I can calculate the distance between the projectile and the orbitPoint to get a radius
and technically you can already use that to get the arc of a circle
how do other games do it?
I know other games where they have projectiles orbiting an enemy
99% of the time they fudge it, and ignore physics completely
tbf I wouldn't mind ignoring physics for this one
I really don't want to get into rocket science to keep an orbit
easy enough, define a fixed path, either circle or elipse and lerp along it
I just don't know how to calculate that fixed path
the projectiles don't start out in a circle
so I can't use that
you got a radius, that gives you a path
if you have 2 radii, that gives you an elipse
idk how the formulas work for that
so research
velocity is physics
you cannot only do half physics, it's all or nothing
like theres a function called transform.RotateAround
I was hoping thatd help
and ngl I'm having issues understanding the documentation
actually it cant be it i dont think
forget Unity for one moment. Go and look at basic geometric methods and then see how they can be impemented using Unity
also, if I have a constant velocity going left, and I have the circle constantly looking towards a point, why isn't the orbit perfect?
the velocity doesn't change, the arc doesn't change
none of the things I found have actual formulas
I know I probably need some cosine and sine function to make it go in a circle
how would I even go about implementing a gravitational constant
I know it's 9.81 but how would that help
or mass
both are done in Unity physics
but I don't specifically need unity physics
I only need unity physics to make the object move forward
I want to change the direction of forward
if that makes sense
and I told you, it's all or nothing, you don't get to chose which bits of physics apply
Easiest way to do this would be to put the projectiles under a parent.
Rotate the parent.
Move the projectiles out to the distance you want, don't move them, the parent rotation will do that for you.
thats a smart way too actually
tho idk how to even find a parent object
as in
the projectiles are prefabs
you give them a parent when spawning them
how can I find the orbitpoint without using FindObjectOfType
look up the instantiate docs
that would mess up other movements
er.. no
and my main problem is still finding the object
because i cant serialize it
what if I want some projectiles to orbit around X, and others to orbit around Y?
hello, how can i change a tile on a tilemap when i click a button?
basically how can I tell the projectile what they should orbit (who the parent should be) before they get instantiated
how do you know where to spawn them now?
I have a script for spawning projectiles and it has a transform parameter
there you go, why would it differ now?
well I need to overwrite some things then
there's also no need to spawn each projectile... have 1 prefab, which is the parent with all projectiles below already.
Spawn the parent where it needs to be, have a class on the parent which then deals with rotation and moving the projectiles outwards
btw this was funny
shoot i pinged mb
hey is there any way to do a transform.Find but with parent objects? transform.Find("App Window/Layouts/" + currentAppName)
or do i just do it reversed
📃 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.
whut
If you're looking to find an object in the scene, you can use GameObject.Find("objectName");
If you want to specifically find a child by this current object's parent, you can use transform.root.Find()
oh yes thanks!!!
You're welcome!
By the way, root object, means the absolute parent here (the topmost transform in the hierarchy)
I made a mistake, sorry, if you want the parent not root, use transform.parent.Find()
oh okay thanks!!!
Hi, my plan in the function: MoveChildToParent is to delete the desired item from the string, but for some reason it randomly deletes another item
https://gdl.space/enoyuqojeq.cs
Can you elaborate more about your problem?
Ok, every time I remove an item, it deletes its name in another string
The purpose of the script is to take the name of an item and put it in a string
There are 3 types of strings as you can see
The problem is with the function MoveChildToParent
So the issue is with PlayerPrefs.DeleteKey("LastTransferredPlayerChild");? and the other DeleteKey?
More or less
It just deletes another item name for some reason
I can show you a video if it's hard for you to understand
Sure
Sorry, I didn't notice the code was out of date
{
Transform parentTransform = parentObject.transform;
foreach (Transform child in destinationObject.transform)
{
if (child != parentTransform)
{
child.SetParent(parentTransform);
Debug.Log("Child " + child.name + " transferred to parent object: " + parentObject.name);
}
}
lastTransferredPlayerChild = "";
lastTransferredWeaponChild1 = "";
lastTransferredWeaponChild2 = "";
PlayerPrefs.DeleteKey("LastTransferredPlayerChild");
PlayerPrefs.DeleteKey("LastTransferredWeaponChild1");
PlayerPrefs.DeleteKey("LastTransferredWeaponChild2");
PlayerPrefs.Save();
}```
I keep trying to make it only delete one item but it doesn't work for me
So the problem is that all the strings got emptied?
Yeahhhh
That's what your code does, when you call that function, you have
lastTransferredPlayerChild = "";
lastTransferredWeaponChild1 = "";
lastTransferredWeaponChild2 = "";
PlayerPrefs.DeleteKey("LastTransferredPlayerChild");
PlayerPrefs.DeleteKey("LastTransferredWeaponChild1");
PlayerPrefs.DeleteKey("LastTransferredWeaponChild2");
PlayerPrefs.Save();```
You delete the all the strings at once
I know, how can you make one specific item be deleted?
You can add an if condition to check if the object's name here is equal to lastTransferredPlayerChild then delete that and then add an elseif doing the same for lastTransferredWeaponChild1 and so on
Hey, all! I'm currently working on a tile-based liquid system using cellular automata and am wondering if anyone would have any suggestions as to how I could potentially go about creating a "pooling" system, creating the actual gameobject with all coordinates and total volume of the pool recursively would be quite easy, but I am wondering particularly how I could potentially create a visual representation of that pool, currently each "tile" is a separate gameobject using it's own logic which I could easily again recursively conform into a "pool" when it settles, however creating a custom shape which represents the "pool" seems to be more challenging, if anyone who's smarter than me has any suggestions as to how I could do that, any advice would be amazing! Currently the main concept would be to calculate layer-by-layer and creating a custom mesh based on those coordinates, however that becomes an issue if a single "pool" layer is obstructed by a tile.
currently my system settles each tile to an average value, however since all tiles are still actively checking it's surroundings (when it doesn't necessarily need to) it is quite laggy. Ideally the pooling system creates a general shape that stores the total maximum volume and it's current volume and would simply lower the mesh as liquid is removed and raise the liquid based on if the pool is added to, if multiple pools connect it would recalculate the entire pool's geometry I assume.
TYSM
if(child.name.Equals(lastTransferredPlayerChild)) //Delete
else if(child.name.Equals(LastTransferredWeaponChild1)) // delete LastTransferredWeaponChild1```
This is an example of what i mean
🇹 🇭 🇦 🇳 🇰 🇸
i have this marker, which checks for things in the middle. how can i make it so it checks towards the pointed corner?
Vector2 screenPoint = RectTransformUtility.WorldToScreenPoint(_camera, _transform.position);
PointerEventData eventData = new PointerEventData(EventSystem.current)
{
position = screenPoint
};
var results = new List<RaycastResult>();
EventSystem.current.RaycastAll(eventData, results);
bool foundCharacter = false;
foreach (RaycastResult result in results)
{
if (result.gameObject.CompareTag("CharacterSelect"))
{
if (result.gameObject.TryGetComponent(out cb))
{
_playerInputController.selectedCharacter = cb._characterInfo;
if (!characterHovered)
{
source.PlayOneShot(hover);
characterHovered = true;
}
foundCharacter = true;
break;
}
}
}
has readme always been here?
yes
sorted it out nvm
hey im using the Child_Light GameObject to spawn more enemies
is there a way to spawn them in without having them as a gameobject?
like prefabs
but i need the code to be attached to it but i cant
u need some script to do the spawning..
no not really
just a way to spawn them in without having them in the game scene
how u reckon that would work?
So im tryign to make a simple pickup system using a tutorial i found online but for some reason the cube objects that i input become invisible to the player when in game mode
prefabs
u would have a reference to the prefab u want to spawn on the script doing the spawning
ye but the prefabs dont have the code and crap
perhaps a static class of some kind
GameObjectSpawner.Spawn(prefabToSpawn, Vector3.zero, Quaternion.identity); mebe
not what im really looking for
the code that ih ave works but is there a way to attach code to prefabs?
yes?
how doe?
yes, by putting a component onto the prefab game object
i don't understand your question
or your problem
same boat friend
The second is not a prefab
u double click the prefab and it opens the prefab view
That's the importer settings for your model asset.
u edit it there
The importer does produce a prefab asset from the model.
oh do i just drag the gameobject in the project files?
But you can't modify it -- it's read-only
yesh thats how u create a prefab
What you can do is create a prefab variant out of the model prefab.
yeah well i tried that too
^ prefab variants are nice
and had an issue with it
and what was the issue?
so i have a script that just makes the prefab follow the player but once i put it in the project files i cant add the thing to follow
that's because prefabs can't reference scene assets
u have to reference the prefab as u instantitate it
they will never be able to reference scene assets
this is supposed to have the player thing
ever
oh so i make the player into a prefab/
no
and change the parameters via that referenence
because then they wouldn't be referencing the player in the scene
You need to do this.
Instantiate the prefab, then tell the new instance about the player.
The "child light" prefab could reference the player prefab, but that would not help them follow the actual player in the scene. It would just tell them about the player's prefab.
spawnedObject.target = whatever;```
you need to pass a rotation as well if you pass a position to Instantiate
oops
coffee's starting to work
The cube is supoast to be visible for the player and it is as long as its not on the pickup layer which i need it to be on since i want it to be an interrectible object
this hangs up alot of ppl
u using camera stacks? for the gun
Your camera is not drawing that layer. Add it to the culling mask
I have a single main camera
sounds like a conflict with the layers u have set up
why not just use a different layer?
theres quite a few of em..
Interactable sounds good
So i just set the camera to the pickup layer?
No you change the culling mask of the camera
Im confused
To include that layer
im reading the thing from unity how and im not rlly understanding nothing
like whats Example? private example i never heard of that and im getting an error every time i use it
whos foo? the player or the thing that follows the player
i know that im supposed to read the bottom part
they're placeholders
it's showing you a pattern
they're anything u want them to be
you're going to need to get used to seeing placeholder names
as long as they're<Type>
it shows you the difference between using a gameobject reference and using directly the component reference, Example and Foo are just examples for a component and function, those can be anything
i know but for example
[SerializeField] private Example _example;
can i use
[SerializeField] private Player _Player; ?
of course
you can do anything
[SerializeField] Florp ridiculouslyLongNameThatYouShouldNotUse;
they're placeholders
[SerializeField] A a;
but then what is private? like yes if i am saying private GameObject then that game Object is private
you can do that too
nothingWrongWithASolidLongName;
private is an access modifier
it controls who is allowed to see that field
i know
private means the variable cannot be accessed by another class
means u can only access that field within the script it was declared/defined
then i don't understand why you asked that question
im not asking what Private means im asking whats private in for example Player _player
but you literally just said you know what it means
i dont think im explaning it right
you aren't, no
private TypeName fieldName;
This declares a field called fieldName that holds a TypeName.
Only code within the same type (so, the same class) can see it
ok
yeah but when i use
[SerializeField] Player PlayerBody; it just gives me a big fat error
then there is no such thing as Player
you don't have a class named Player
If all you need to do is tell the instances where the player is, you can give them a Transform
But you probably want to have a "player" component
or use ur actual script name that u have for ur player
wait in this code im calling on another class?
yes
read the entire page again
Example.cs
it cleraly explains exactly what is what
well that explains alot
The type: class, struct, interface, enum, must exist when using it to declare a field (variable) . . .
you've been around a while.. u been coding without knowing this?
If you don't know how classes work, you probably want to consult !learn ..
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
i didnt know that the script was talking about classes
well what would it be talking about..?
the only other ways to create new types is declaring structs and enums
yea, thats what we're saying tho.. by looking at the code and using context clues u can figure out whats happening..
if you have the fundamentals.. but i think u may be lacking a bit of information.. so i agree with the !learn content
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
and all component types are classes, because they all derive from the Component class
Every script has a class, interface, struct, or enum. That's the only way to create a type . . .
oh right, interfaces! i forgot interfaces!
oh snap.. i couldn't kill it with codeblock interesting
time for a ZWJ
!learn
perfect
😐 ive been bested
https://gdl.space/pewesarida.cpp
I am trying to make a clamped velocity script that will clamp the velocity at a select amount so I am not beaming through my level. I got the forward velocity to work but for some reason my sideways velocity will not go to the correct maximum or minimum. Its always maxing at 1.14?
That's why your scripts have . . .
public class InsertScriptName
Unfortunately only works for 3D at the moment 😭😭
is this using a rigidbody i imagine?
yeah
clamped is being called in my FixedUpdate
I can get the full script if you want
can u share a snippet of ur logic?
btw, you can just use Vector2.Project instead of dotting and multiplying
yes please
that'll also save you a few lines since you can use ClampMagnitude
whoa, epic clamp function
I hope 😢
One thing is if you're using AddForce that doesn't get applied until the physics simulation and isn't visible to your clamp. It's annoying as hell hence why I made a whole asset (partially) to make this simpler. Ofc it's only for 3D sadly
simulated physics ftw glad i use a CC most days
guys, how to calculate new position from rotation (mathematics.quaternion) , float3 (position ), and speed ?
you can rotate a float3 with a quaternion
Is the speed in your forward direction?
yeah
so you can rotate a forward vector with your rotation
Ok I'll see what I can do witht he Vector2.Project and clamp magnitude.
then multiply that by your speed
If so it's:
Vector3 vel = rotation * Vector3.forward * speed;
Vector3 newPos = Time.deltaTime * vel + oldPos;```
(or the equivalent mathematics functions here)
AAAAAAAAAAAAAAA
yeah, one of the overloads is quaternion and float3
Did you mean Vector3 on this? Vector2 doesn't have this in Unity Docs
oh, is there not one?
it'll work the same
you'll just have to cast back to vector2 (either implicitly or explicitly)
is vscode deprecated or something? heard it doesn't work anymore
you use the "Visual Studio Editor" package now
hang on i need to take a photo of a cool bug
got it
wait vscode works?
!ide
okay bet
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
thank you
make sure to uninstall the "Visual Studio Code Editor" package if it's present
oh, it appears I do have it. Does it make a difference?
Yes. That's the old, deprecated package.
Also, you need to be on a least 2021
(see the VS Code section of that bot message; it goes through everything)
alright, thank you.
Interesting, did not know this . . .
Newer versions of unity don't install it at all
for a while you got both installed, which was annoying
VSCode works great now. I used to have a lot of trouble with it
the Visual Studio Code Editor package produced project files that required VSCode to...i'm not really sure, use older analysis/.NET? I'm kind of confused about that actually
it was slow, though
i prefer vscode over vs cause of how lightweight it is
it would take several seconds to do completions
You also had to manually install analyzers
I used this for a while https://github.com/Chizaruu/com.tsk.ide.vscode
it was still fiddly, though
I still have that analyzer DLL in my project. I should delete that and make sure it wasn't actually being used still...
Would it be better to change how I am applying the forces then? Or will this be fine for now? Because the forward and backward velocities clamped just fine so I don't think its getting in the way of my clamps
hey is there any way to do a transform.Find but with parent objects? transform.Find("App Window/Layouts/" + currentAppName)?
transform.parent
however, comma,
maybe there's a better way to do this
e.g. having a dictionary to look up app windows with
like transform.parent and path to way up?
There's only ever one parent for each transform
So no need for a search
were you not already told about transform.root ?
i tried but didn realy wowk
i can assure you that transform.root does what it says on the tin
your problem was more likely that you're digging around in the hierarchy
which is very brittle
you could write a clamp function that u can pass in ur variables to
a generic type function that doesn't care about anyhting but the values u give it and could run it thru that whenever
Hey guys, I wanna buy a desktop pc to start programming in Unity. Mostly 2D Games. What specs should I start with? I don't wanna spend a kidney on a PC
what pc do you have rn
I have an old laptop, really old one. i5-6300U, 8GB DDR3, no gpu😂
u dont need much.. 4 gig of ram.. i5, windows7 or higher graphics card with dx10 @outer hollow
how about mathematic quaternion to float 3 ? how to do it ?
but thats bare minimum.. i'd get atleast an 16 gig machine
I am not looking to play any games on it whatsoever but I do want it to be quite capable of running certain softwares... I need 32gb ram, but i dont have any idea of what gpu or cpu to get. I dont need anything too fancy..
I can get like a 4060 Ti or smth but I just dont really think Ill need it
u dont need a 4060ti
1060 would be good enuff
something with atleast 4gb of vram
Wow, unity doesnt need much today
Ok ok, how much ram should i get? I only want like unity, an ide and google running in the background
u said u want 32
I want but idk if i need it😂
i run 32.. but 4 would be the minimum. 16 is reccomended
Okay, thanks
Windows will not enjoy 4gb 
Yh😂
facts.. but its possible
Also true
More memory is useful for running multiple things at once
like Blender and Substance Painter
if ur like me and u multitask with 2 monitors
it also means more files get cached
https://gdl.space/dugidulego.cpp
I am probably missing something obvious but it keeps ignoring my maxBackward Velocity that is set to 1.5 in the inspector when clamping my upward/downward velocity. It keeps maxing out both at 3
sometimes i open 3 unity projects at once
Tried clamping magnitude with a positive and negative projection vector3 but clearly wasn't it
3? thats chump numbers 😈
Me with 4 Rider instances, 8 vscodes, 3 Unity instances, fork, steam, docker, chrome with 100 tabs, many file explorers 
^ brother from another mother
ah, if you want separate forward and backward velocities, you need to handle forwards and backwards separately
...which actually calls fot a Dot, haha
what are u using docker for 🧐
float forwardDot = Vector3.Dot(upwardProjection, transform.up.normalized);
if (forwardDot > 0)
clamped = Vector3.ClampMagnitude(upwardProjection, maxForwardVelocity);
else
clamped = Vector3.ClampMagnitude(upwardProjection, maxBackwardVelocity);
like so
gotcha lol. Also the 1.14 value on my sidestraifing is still happening both ways. Very unsure how to get it workin
The magnitude of a vector is always positive
so your code around lines 21-36 doesn't work
I'm facing a problem related to the Image that is getting destroyed. When I run the game, on the game scene I have a settings icon Button and when I click on it, it shows the settings screen, within the settings screen, I have "Restart, Resume, and Home" Buttons. When I click on the "Restart Button, it's destroying the Settings Screen Image and the script. Can someone help me fix this issue. I want the Settings Screen Image to remain on scene
Game Manager Script: https://gdl.space/ejumahivat.cs
SettingsImage script: https://gdl.space/eyituvegav.cs
one thing to remember is that the velocity is in world space
maybe you're rotated a bit?
in that case, you'd see a lower Y component when moving sideways
since some of your sideways movement is in the X direction
Even if, when its set to 50 its still doing 1.14 and the z is 0 with y being nearly nothing
what function are u calling when u click Restart
get rid of clamping entirely
perhaps something else is interfering
Restart game method
roger, will check
well then dont disable the settings menu
actually if u load a new scene that settings screen wont exist anymore
a different instane of it would..
If I don't disable the settings screen image, it stays on screen upon restart which makes it unplayable.
clamped variable here is going to be the same as clampedUpwardVelocity was right?
Yes but just set to inactive
right: it's going to be the velocity in the up direction
whether you're going up or down
well i dont see where its getting destroyed.. but if u load a new scene everything in that scene is going to get destroyed.. unless u have it w/ DDOLs
why do you think the settings object is being destroyed? are you getting an error about it being destroyed?
and where is this settings object located?
hes loading a new scene directly above it ^
yeah, if it's in the old scene, it's going away
ur gonna have to find a way to tell the new scene what state its in
or make ur settings stuff its own scene.. and keep it loaded
load ur game scene on top..
something like this... where u have a scene loaded at all times w/ ur settings stuff
@rocky canyon @swift crag Please allow me to explain:
Settings Screen image is initially set to inactive and when I load the game, click on the in-game settings icon, it sets the settings screen image to active within which I have 3 buttons (Restart, Resume, and Home).
When I click on the Restart Button, it's destroying the instance and from the Game Manager script (both settings screen image + settings Image script) due to this reason, if I click again on the in game settings icon, it's not showing the settings screen image
Works perfect, thx! Now will take a look at the straifing
have u heard of DDOL?
put the settings object in DontDestroyOnLoad too, then
you're already doing that for the GameManager
Yes
i think thats ur answer.. unless u wanna rewrite ur settings menu
It's an Image, so how to use DDOL for an Image ?
its a gameobject innit?
Should I attach a script to Canvas itself that contains DDOL?
DDOL(urobject);
coulddo it in the gamemanager
since it already has a reference to it
DontDestroyOnLoad is called on a game object
you're moving the entire object the settings menu lives onto into the DontDestroyOnLoad scene
and you don't want to just move the object with the image, yes
It's a canvas Image
you could put a component on the canvas that moves its object into DontDestroyOnLoad
You are right, something funky with my addforce. Its adding a force but keeps clamping at 1.14 instead of going higher
@swift crag @rocky canyon thanks a lot guys ❤️🙏
progress
Hi
Helwo 👋
{
Transform parentTransform = parentObject.transform;
foreach (Transform child in destinationObject.transform)
{
if (child != this.transform)
{
child.SetParent(parentTransform);
Debug.Log("Child " + child.name + " transferred to parent object: " + parentObject.name);
if (child.name.Equals(lastTransferredPlayerChild))
{
lastTransferredPlayerChild = "";
PlayerPrefs.DeleteKey("LastTransferredPlayerChild");
}
else if (child.name.Equals(lastTransferredWeaponChild1))
{
lastTransferredWeaponChild1 = "";
PlayerPrefs.DeleteKey("LastTransferredWeaponChild1");
}
else if (child.name.Equals(lastTransferredWeaponChild2))
{
lastTransferredWeaponChild2 = "";
PlayerPrefs.DeleteKey("LastTransferredWeaponChild2");
}
}
}
PlayerPrefs.Save();
}```
Anyone know why it doesn't work?
What doesn't work?
explain doesn't work
!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 adding forces consistantly. There is no drag or gravity so very weird
forgejo and act
oh its my spacebreak somehow. I forgot to add a xAxis condition to the coupling if statement 🤦♂️
Hi guys, so I have this problem when setting a variable (AccelerationProgress) to zero when the current state is walking or running (meaning right when the player starts walking OR starts running, that variable becomes a zero). The problem is that in my line on code, if the player is walking and then runs, then that variable will not be set to zero. I have no idea what I can do to solve this issue, but I do feel like storing the current state and the previous state and then comparing them might solve this issue. Before doing that tho, I just want to confirm with you guys if that is a good solution or if you have another easier solution.
Here is my line of code:
if (CurrentState != State.Running.ToString() || CurrentState != State.Walking.ToString()) AccelerationProgress = 0;
The purpose of the script is to take the name of an item name and put it in a string, but when I want to remove the string via MoveChildrenToParent but it doesn't work well...
https://gdl.space/muriroximu.cs
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
!docs
I cannot seem to connect my movement functions to the Events in my Player Input component. They are public and I have no compiler errors at the moment and I believe the correct script is attached (as in it is definitely the correct script unless I am misunderstanding what that slot is meant to take).
(not sure if this is the right channel. Feel free to let me know if this should go somewhere else and I'll delete and repost it over there)
show the code
you need a public function with correct parameters
to match the delegate
you dragged in a script. Not a game object with the script
Not sure what this means... should I be dragging in the script component in my player object or the player itself?
player
ah, I think I can see now... fingers crossed.
I have a problem when using event system, I want to broadcast a event on Start().
Putting the subscribe part of other scripts doesn't work, the Start() method from the Manager script might executed before the other subscribers.
Then I moves the subscribe part of subscribers from Start() to Awake().
But it collides with the Awake() function in the Manager script to initialize a instance of itself, the subscribers cannot find the instance of the Manager.
So what is the optimal way of doing this?
❔
If lastTransferredWeaponChild1 is not being set to blank, then child.name is not equal to it
So log both of those and see what they are
you need to think about the lifetime or your objects and the order that your logic is supposed to run in - generally, Awake is for constructing the script/object itself, and Start is for initialising it with references to other scripts/objects, a couple things you can do:
- Call things when you want to call them. If you have a few objects that need to do things in order, and you're spawning them in/out/whatever else, have a method to organise that, e.g
void Initialise() {
Manager manager = CreateManager();
List<Child> children = CreateChildren();
foreach (var child in children) {
child.Initialise(manager);
}
}
- Rely on Awake/Start, but set the script DefaultExecutionOrder to guarantee which script runs first https://docs.unity3d.com/Manual/class-MonoManager.html
does using a coroutine to make the call of the event delayed like 0.001 seconds help?
what do you think is the best way to handle items in a player inventory? is List<GameObject> fine for holding items?
Hey, so I've been wanting to make an AI for a capture the flag demo. I have been researching GOAP and it seems that is too much for what I need, yet a basic FSM solution is still not effective either
it can "work" in isolated cases, but it's a really bad way of doing things imo
Lists are fine, but you should probably have a custom component that determines what an "Item" is
ok, thanks
So trying to find a middle ground between GOAP and FSM. Behaviour trees is another solution but struggling to see the advantages of that
I see, so I just call the functions of my subscribers in their own Start() will be better rather than call by the manager
Completely depends on what system you are trying to make. If it is a simple horror game where you can pick up things and drop them, a list is fine. But if it is a whole interactive UI inventory system then you may want to look into dictionaries. Again, depends if you need it serialised or not too
I'm not sure what you mean
ok, i think lists are fine in my case. thanks for answer
because I call the event on Start() is equivalent to do all the stuffs on the Start() of each subscriber, so doing the latter should work as intended
I'm still not quite sure what you mean, it sounds a bit like you've tried to use events in a place where it doesn't make much sense to use them at all. If your objects/subscribers can happily initialise themselves in Start() anyway, there's no need for an event
Then a behaviour tree sounds perfect for what you want
perhaps you should share the code you have currently as it doesn't make much sense
Definitely use a custom type (class) to hold the items. A list will work and ia easier when adding/removing items . . .
I guess so, there is no need to use a event on Start(), I guess I figured out the way. Thanks for the help ❤️
fine.
My only gripe is Unity doesn't come with a visual graph editor
muse behavior exists and is free
Ahh, you don't need one for a behaviour tree. It can be entirely code if you want.
But yeah, what boxfriend said
Yep, don't need one, true. Would be nice though, but oh well
Did you see what boxfriend said. Because there is one available
Yep, I'll consider it
I am still trying to get this player input component working. For some reason the move call seems to want to call a function with a signature that lacks any input value... but surely that isn't right? I need the input value from the move input to know which of the four directions the player is moving. I am very confused... How do I get the Vector2 into the function if the function may not have any variables in the signature?
Code Link:
https://pastebin.com/1dLzxNNs
(I got OnMove into that slot by commenting out the content of OnMove and cutting out InputValue then saving and only then was it available... when I added all that stuff back in it now says the function is missing)
The parameter needs to be CallbackContext
As it says in your image
"Move (CallbackContext)"
How do I get the Vector2 into the function if the function may not have any variables in the signature
your method will need to accept an InputAction.CallbackContext parameter
Not sure I understand. Is the problem that the type of my InputValue is input and not InputAction.CallbackContext? If so, I'm not entirely sure how I would go about making it that but I can probably figure that out.
your OnMove method needs a parameter of type InputAction.CallbackContext
As well as the one of type input? or instead of?
wtf are you even referring to there?
i am referring to this method: public void OnMove(InputValue input)
the type of the parameter needs to be InputAction.CallbackContext
not InputValue
In my current function there is a parameter InputValue. Is what you're talking about meant to replace that or is it seperate.
Ah. Replace. Alright.
Still does not work
were you somehow confusing the parameter's name input with a type? because if so, you may want to refresh yourself on the basics of c# to learn the difference between types and identifiers
Yeah I think I was. Possibly mainly that I'm tired. I know the concepts just new to C#.
Hi guys, so I have this problem when setting a variable (AccelerationProgress) to zero when the current state is walking or running (meaning right when the player starts walking OR starts running, that variable becomes a zero). The problem is that in my line on code, if the player is walking and then runs, then that variable will not be set to zero. I have no idea what I can do to solve this issue, but I do feel like storing the current state and the previous state and then comparing them might solve this issue. Before doing that tho, I just want to confirm with you guys if that is a good solution or if you have another easier solution.
Here is my line of code:
if (CurrentState != State.Running.ToString() || CurrentState != State.Walking.ToString()) AccelerationProgress = 0;
oh god why are you storing the state as a string instead of just using whatever type State.Running and State.Walking are?
anyway, more info about how you are transitioning from states would be helpful to determine the best way to go about this
I don't understand, how am I supposed to store the state?
with numbers?
is State an enum?
yes
then use that
there is no reason to convert it to a string to store it in a variable
oh I see. I will change that
can I just send you my entire code?
sure, use a bin site like the bot shows 👇 !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.
holy hell this is a mess. you're going to need to refactor this if you want to do this in a sane way because you'll need to check what state you are transitioning from when you go to transition into the Walk or Run state
or if you just want a bandaid solution, you can just check what the current state is when you go to call Run() or Walk() and just reset the AccelerationProgress if you are in the opposite state
The purpose of the script is to take the name of an item name and put it in a string, but when I want to remove the string via MoveChildrenToParent but it doesn't work well...
https://gdl.space/muriroximu.cs
Just gonna ignore me then?
#💻┃code-beginner message
check what the current state is when you go to call Run() or Walk() and just reset the AccelerationProgress if you are in the opposite state
How do I do that?
with an if statement
private State myCurrentState
if (myCurrentState == State.Running)
Or a switch if you have a bunch of states (I did not look)
yes I am aware of that, but I don't know what the condition must be to check if they are in the opposite states
aethenosity just showed you
by "opposite state" i am just referring to those two states you are having trouble with
ahhh ok yea I get it hahaha
you would be much better off if you built a proper state machine where you transition into a state explicitly and explicitly transition out of it as well instead of this just possibly random hopping into and out of states with no control over what happens when you enter/exit a state
these simplistic if/else chain state machines don't allow fine grained control over what happens when you enter or exit a state and so you end up with spaghetti when you try to do anything deeper than just moving in a specific way during a state
adding a SetState method that handles the transitions can help with that. I use that for systems that are just a few fixed states.
im sorry, this is the first time I have used an enum. When ever I use an enum, I always use .ToString. just one more question, aethenosity used cs State.Running and compared that value to myCurrentState, then how is myCurrentState being saved
It's a variable
strings and enums are identifiers. So technically making an enum into a string is quite redundant
It's saved... in whatever scope it's declared in.
But yeah no reason to use ToString most of the time.
how do I do that? I dont understand 😭
is the variable a string?
no
It's a State
enums are custom types
they're datatypes just like int string SomeClass MonoBehaviour etc
State myCurrentState; is a variable of type State named myCurrentState
using State as the type for your CurrentState variable was the first thing i suggested to you
yea your right 😅 I didn't seem to understand what you meant here
You simply set it by:
myCurrentState = State.Running
you're just creating a whole bunch of garbage and unnecessary conversions when you ToString an enum just to store it in a variable. you're also likely increasing the amount of memory you are using in many cases when doing that since an enum is just a regular integer with a fancy nametag at compile time so it's just 4 bytes where as the strings vary in size based on the number of characters
Or whatever state you want
ok well thank you! ill apply these changes
Strings are also slower to compare and use more memory - for the most part.
you also lose some sanity checks from the compiler
someString == "totally bogus name!!!" is fine
myEnumVal == MyEnum.IMadeThisUp is a compile error
this gives an error? but I just did that right now and it is not giving me any errors
presumably you used an enum value that actually exists
i'm talking about a bogus name
If the enum value does not exist, it would give an error
"i made this up" was misleading since the entire thing is made up :p
ahh well yea that makes sense
L'eci n'est pas un enum
One of the more useful uses of enums is it's got type constraints, so you aren't just comparing some raw string values
a cool thing about enums is when you use them in a switch expression
int result = myEnumVal switch {
MyEnum.Foo => 1,
MyEnum.Bar => 2
};
You get a warning if you skip any enum values
Annoyingly, you also get a warning if you don't have a default case (because it's possible to cast an int into a bogus enum value that doesn't exist)
i turned that off
that way, if I introduce a new enum value, all existing switch expressions get warned for missing the new value
adding a default case winds up hiding the problem!
oh yeah they look nice in switch statements too is always a plus
public float ToSliderValue(float value) => kind switch
{
Kind.Linear => value,
Kind.Logarithmic => Mathf.Log(value, 2)
};
public float FromSliderValue(float sliderValue) => kind switch
{
Kind.Linear => sliderValue,
Kind.Logarithmic => Mathf.Pow(2, sliderValue)
};
I used to really abuse the heck out of strings, but enums are life now.
Probably some bad python habits
huh, this is interesting because this switch case starts with cs int result = myEnumVal. The way I have learned it in C is much different. You have to add an argument that goes over each case (ex case 1, case 2, etc.) until it finds a match.
I have to start learning how switch statements work in C#
It's not a switch statement!
It's a switch expression
an expression is something like 3 + 4
statements contain expressions, amongst other things
switch(myEnumVal) {
case MyEnum.Foo:
result = 1;
break;
case MyEnum.Bar:
result = 2;
break;
}
a similar switch statement
hi, does someone know how to fix this error? 😅
The proper name of that class is TMPro.TextMeshProUGUI
You can either:
- write the full name, including the namespace
- add
using TMPro;
configure your !IDE
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
btw I just found a flaw in this code. For example, if I am running, this value would be set to zero non stop only until I switch to my walking state.
if (CurrentState == State.Running || CurrentState == State.Walking) AccelerationProgress = 0;
Why are you doing that
I want an if statment that will reset the AccelerationProgress only once untill these conditions are met
If you are running or walking then set acceleration progress to 0 every frame? (Assuming update)
Just check if the current state is running when you want to start walking and vice versa
Two separate checks
Or take my better advice of completely refactoring to a more robust state machine that has entry and exit methods for each state so you have better/more extendable control over everything
I don't know how to make that tho. What is a state machine and an exit method?
and how do I apply it to what I am trying to do?
yes. this code is running constantly
ah thanks ^^
A state machine runs specific behaviour for an object when it's assigned to. Think of it like Turing machine, it loads a specific class for the appropriate type, that runs specific design behaviour for that state, and then exit when either the manager that holds the state machine decided to load a new state to it or when the state have specific instruction to load a new state after it's finished with it's behaviour. Here's a video that cover about state machine in Unity: https://www.youtube.com/watch?v=G1bd75R10m4
Sign up for the Level 2 Game Dev Newsletter: http://eepurl.com/gGb8eP
In this video, I'm going to teach you how to code a simple State Machine in Unity.
#Unity3d #UnityTutorial, #GameDevelopment
Have you ever written a method with two paths of execution? It probably had an if statement based on a member variable, right? But then your requirem...
ohh thank you! I needed that
i still wonder to this day how the hell the rollercoaster tycoon dev made the game in assembly
and im over here struggling with c#
Not all great assembler programmer started to work in game industry. They had experience of failure and tries before they were able to pull off such great success.
Not to mention, but I recall a developer in Activision talked about the Z-depth bug in World of Warcraft (or was it something else?), where a character would be clipped over a wall, due to of how the game engine handles the draw implementation between the environment and the playable character.
its because you have more restrictions to what you can do, you force yourself to learn more
c# is pretty forgiving and there are soo many ways to do something
i truly hope i dont pull a yandere dev
and get clowned on for poor code
but i have so many else ifs
and dont know how else to implement it
C/C++ requires extensive care with memory management and code structure. C is very abstracted, C++ includes classes and object orientated programming is made possible, but comes with high risk cost of memory violation. C# makes it memory safe, but at the cost of performance dealing with garbage collector.
You are in a beginner channel, where it should be easy to ask for help and recommendations.
there is nothing wrong with having a bunch of else if who said its bad ?
no like
5 else ifs
i think that's an issue
I had bigger
If you have too many conditional statement, then consider refactoring it down to simplier statement.
I think the best way to approach C# is to make your game as simple as possible, describe what your game absolutely need to function, and then branch out from there. If you start C# by detailing a function that doesn't impact your entire game, then you need to take a step back and focus on your pillar of the game.
switch is the same thing as a bunch of else if
Under a certain amount. Then it becomes a jump table if possible
Becauae the neat thing about C# is that once you describe the abstract class of what your game does, you can create override class and inherience to define specific behaviour for your game. E.g. An IPlayer interface can be applied to a character or vehicle, depends on how you define it.
I would say interfaces are more on the Composition side of things than inheretence
for something where theres lots of different enemies which do different damage and effects
what would be a clean way to code that
thats a very vague question
cause i can only think of a big script of if statements
what way "clean"
whoa, that's a big one . . .
each enemy should have their own behavior and not having to check any tags or anything
simple solution is to use OOP (inheritance) for the enemy classes . . .
maybe here you can use Inheretence or abstracting the class
override the methods in each enemy etc
better solution is to create separate classes and stack them on enemies to create their specific behaviour . . .
indeed. Unity is component based, make a bunch of components
vague answear for vague question here: there is tons of design patterns to try out. Combinations of factory and inharitance/composition and maybe even state machine 🙂
i will look into those things thanks guys
could you explain this a little more please
I am getting 6 The referenced script (Unknown) on this Behaviour is missing! errors and I haven't the slightest clue what the problem is. I have checked all my scripts and the public class is indeed named the same as the script file and I can't find any object which does not have it's script component attached correctly... also the errors do not highlight or indicate toward any asset or gameobject. How does one debug such an error?
e.g., i have two turrets: both have a Shoot component and a FindTarget component, but TurretA has a Rotate component while TurretB does not. this means TurretA can find targets in range as it swivels while TurretB can only find targets that come into its range—since it doesn't rotate. by stacking components, you can add/remove functionality, and this changes their behaviour . . .
its probably one of your objects/prefabs with a missing script
or you saved changes of script during playmode
I think it might be this... how do I fix it?
there is nothing to fix then
its not gonna be there again
the old script because now its a different script as far as computer cares
hmm. I kept getting it. Might be a comedy of errors on my part though.
like I said unless you have a prefab/gameobject somewhere with a missing script, or broken meta. This only happens when you Compile scripts changes while in Playmode
I don't have any prefabs afaik and all my gameobjects have their scripts attached (there is only a few so I was able to check them all manually)
It's probably fine.
so yeah just be aware of saving script changes while in playmode it will happen
you just restart the simulation and ur good to go
the same applies to enemies. all of them will have a base Enemy script, but you can add individual components to give them different behaviour. adding a Jump component will allow any enemy with that component to jump, while others will not. each GameObject will have a separate instance of Enemy; you can use prefabs to give certain enemy types different values for attack, damage, health, etc . . .
That's general idea behind having component base architecture. Don't be afraid of having multiple scripts, just try to not couple them to much.
in most cases with unity it will be interchangeable: scripts / monobehaviours / components.
but scripts can also be other stuff. like scriptable object or just plain c#
if its on a gameobject, its a component
For some reason the button variables in this script are not serializing (I think that's the right term) in the editor. I want to be able to tell the buttons whether to be visible in this script and so need their object but I am not able to get a slot for them.
damn. it really were that simple weren't it. Thank you very muchly.
sometimes it is , gotta keep an eye out what the IDE puts there on their own😛
hmm... I get the feeling I may have switched it to UIElements because it looked like that had the ability to change the object's visibility. UnityEngine.UI.Button seems to lack the ability to change that.
yeah don't think there is a need for UI Toolkit buttons to be in inspector, they constructed different than old GUI with binding and all that
you can just hide the gameobject no?
Ideally yes. That is the goal.
Doh. If I'm doing that I should have the gameobject as the variable. Pardon me.
you can access the gameObject
from component
every component has a .gameObject property
myButton.gameObject 🙂
Yep. Just trying to look up how to set it to invisible now.
I believe it was something like gameObject.SetActive(false); but can't check that right now
yeah that's right. I've got that.
📃 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.
In the MoveChildrenToParent function the strings are not deleted well
https://gdl.space/itokuhepiw.cs
How to fix it? 🤔
Jesus fucking christ I know you haven't blocked me, I can react to your posts, why do you just ignore my answer every time you repost this same question
#💻┃code-beginner message
Hey, I didn't block you 😂
I just forgot to respond to this, sorry bro
Three times?
I know 💀
Three times, and then reposting your question two times?
I just went to try to fix the code after I wrote it and I didn't look at the discord
I have no reason to lie 😅
Well I will try what you said
What is a good way to troubleshoot the input system slowing down?
@polar acorn
{
Transform parentTransform = parentObject.transform;
foreach (Transform child in destinationObject.transform)
{
if (child != this.transform)
{
child.SetParent(parentTransform);
Debug.Log("Child " + child.name + " transferred to parent object: " + parentObject.name);
// Logging the values for debugging
Debug.Log("Comparing child.name: " + child.name + " with lastTransferredWeaponChild1: " + lastTransferredWeaponChild1);
Debug.Log("Comparing child.name: " + child.name + " with lastTransferredWeaponChild2: " + lastTransferredWeaponChild2);
if (child.name.Equals(lastTransferredPlayerChild))
{
lastTransferredPlayerChild = "";
PlayerPrefs.DeleteKey("LastTransferredPlayerChild");
}
else if (child.name.Equals(lastTransferredWeaponChild1))
{
lastTransferredWeaponChild1 = "";
PlayerPrefs.DeleteKey("LastTransferredWeaponChild1");
}
else if (child.name.Equals(lastTransferredWeaponChild2))
{
lastTransferredWeaponChild2 = "";
PlayerPrefs.DeleteKey("LastTransferredWeaponChild2");
}
}
}
PlayerPrefs.Save();
}```
Like this?
If you ask, they don't respond
give them more than like 10 seconds to respond. parsing that giant block of code and trying to figure out why you've chosen to do any of this in this manner is going to take a minute
Especially considering you ignored digi for hours
It was not on purpose 😅
Well, just keep that in mind before complaining that digi didn't immediately respond. We all tab back and forth here between work, so it may take a moment
Don't worry, I appreciate this guy
Also it is worth scrolling back to see how people responded to the original time you posted the question before reposting it to see if you've already been answered... people tend to get annoyed if they are repeating themselves at a brick wall.
I know I already did that, thanks anyway!
you know, I dont see any difference in that code from the last 3 times you've posted it
I dunno man try posting it two more times
Also you don't have to ask "like this" you can just run the code
Because I couldn't solve the problem so I went back to the original code 🤷♂️
Because maybe I didn't put them right, logging is not my forte
Well, if you run the code, and it says "Halibut" you can probably guess something went wrong
Ok the logs work, you were right, the code had to be run several times
So, since it matches the second one, it blanks that one. Since it does not match the first, it doesn't blank that one
That seems to be exactly the behavior you've coded in
{
if (Input.GetKey(KeyCode.W)) //move forward
{
newCameraPosition += transform.forward * cameraMoveSpeed;
}
if (Input.GetKey(KeyCode.S)) //move backwards
{
newCameraPosition += -transform.forward * cameraMoveSpeed;
}
if (Input.GetKey(KeyCode.D)) //move right
{
newCameraPosition += transform.right * cameraMoveSpeed;
}
if (Input.GetKey(KeyCode.A)) //move left
{
newCameraPosition += -transform.right * cameraMoveSpeed;
}
}``` Is this not frame independent? It slows down massively the more game logic I have.
The entire Input system is suddenly sluggish
Where do you call HandleDirectionInputs
In the Update() method
So, why would it be framerate independent?
So do you have an idea how to change the code?
You're calling it in Update and not using any sort of deltaTime
What are you intending for the code to do? It looks like it's blanking out whichever field matches a certain object's name
and that appears to be what's happening
https://docs.unity3d.com/ScriptReference/Time-deltaTime.html
you need to scale it w/ deltaTime
or, call it from FixedUpdate (so its fixed)
As you see in the video, it will simply pick up the name of the item
if you add a constant amount to your position every frame, your speed will depend on your framerate
more frames, more +=s
And the name of that item does not match what you're comparing it to, so it doesn't clear out
Which end of that comparison isn't the value you expect it to be
was this to me?
yesh
No, it adds the names properly, the problem is that it doesn't delete the names properly
Here's the video again if you need
okay thanks Ill try that out, didnt know about FixedUpdate
fixedupdate would be a bit of a hack
As I've said, it doesn't clear out the LastTransferredWeaponChild1, because it doesn't match child.name. Which of these values is the one that isn't what you expect it to be
you'd still want to factor in deltaTime there
true u should scale it for smoother movement
and camera movement should absolutely be happening in Update, not FixedUpdate, or you'll get a horribly jittery camera
you'd be off by a factor of 50 (by default)
this script currently checks if i can click a bar or not using a timer. everytime i click the bar, it does a function however when i can't click it, the timer counts up to its intended value and when it does, i can click. however it doesn't seem to to be doing that for some reason?
https://hatebin.com/bqfyyrqeye
ya, what i mean tho if he scales it he can keep it in Update();
but he didnt even know of fixedupdate.. lol soo he learned a bit heh
kinda all ties together, when i was learning knowing when to scale w/ deltaTime and when not to.. and how the update loops all work was like 1 big session
even if you use it in FixedUpdate, you should multiply in deltaTime; otherwise you move 50 times faster than you intended to
I'm a bit confused on how to approach this systems problem for a Pokemon clone. What's the best way to handle battle states?
Do I create a BattleManager that changes the game state depending on whether or not they are in battle? If so how do I toggle the active game state?
The way I'm doing it right now is toggling between the two cameras which is very janky and buggy.
Any thoughts appreciated.
So you are suggesting something like this? newCameraPosition += -transform.right * cameraMoveSpeed * Time.deltaTime;
because it doesnt work at all
your cameraMoveSpeed might just be super small because you were probably previously compensating for it being in Update
I've left the method in Update() while I tested * Time.deltaTime; and the camera not longer moves at all
because now the speed is too low
what is the actual value of cameraMoveSpeed
0.1f, but shouldn't it still move a bit?
oh lord
that would move one tenth of a unit per second
say your speed is 5, lest say 0.23(deltaTime) thats about 1.15
5 * 0.23
0.1 units per second
Alright this is starting to make sense lol
cameraMoveSpeed should be the number of units you would like for it to move per second
I have so much fixing to do now that I know this lol
Sorry for delay
Can you give me an example of the part that needs to be changed in the code? 🤔
I literally cannot know what the problem is until you tell me which one is the value you don't expect it to be
this script currently checks if i can click a bar or not using a timer. everytime i click the bar, it does a function however when i can't click it, the timer counts up to its intended value and when it does, i can click. however it doesn't seem to to be doing that for some reason?
https://hatebin.com/bqfyyrqeye
What is it that it's not doing that you expect it to be doing
You described several behaviors without specifying which one isn't happening
Hey, for some reason in my water cellular automata simulation script randomly some of my water objects, are disabling their script and collider, does anyone know if "gameobject".isActive = true/false overrides a potential boolean variable I have declared which would be causing that?
That is the only thing I suspect could be doing that.
They won't just deactivate themselves for no reason, something is calling .enabled on them
Yeah, I really don't know. I have nothing in any of my game's scripts calling .enabled at all. Super weird.
Put a log in OnDisable on your script and see where it's called from
How would I do that, definitely would help diagnose it!
Just put a log in OnDisable. The stack trace should show what calls the function to let you know what's disabling it.
https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnDisable.html
ah, I see thank you!
sorry for the confusion! the unexpectedness is happening from lines 30-34 not running at all
disabled
UnityEngine.Debug:Log (object)
LiquidScript:OnDisable () (at Assets/Scenes/Liquid Testing/LiquidScript.cs:297)
UnityEngine.Object:Destroy (UnityEngine.Object)
LiquidScript:PoolJoinPool (UnityEngine.Vector2) (at Assets/Scenes/Liquid Testing/LiquidScript.cs:229)
LiquidScript:CheckPool () (at Assets/Scenes/Liquid Testing/LiquidScript.cs:166)
LiquidScript:WaterSimulation () (at Assets/Scenes/Liquid Testing/LiquidScript.cs:292)
LiquidScript:FixedUpdate () (at Assets/Scenes/Liquid Testing/LiquidScript.cs:36)
Would this be due to the "Destroy"?
It should be destroying the gameobject all-together not disabling no?
Then timeRemaining >= GameManager.gameManager.sellTime is never true when canClick is true. Try logging those three values
foreach (Transform child in transform.parent)
{
if(child.transform.parent.childCount == 1)
{
Destroy(child.transform.parent.gameObject);
child.transform.parent = GetLiquid(gameObject.transform.position, joinDirection).transform.parent;
//child.GetComponent<LiquidScript>().isActive = false;
}
child.transform.parent = GetLiquid(gameObject.transform.position, joinDirection).transform.parent;
//child.GetComponent<LiquidScript>().isActive = false;
}
``` here's the script that seems to be calling the destroy, does Destroy() recursively on children not destroy them?
OnDisable is also run when the object is destroyed or when the object it's on is disabled.
Ah, strange. Would there be any reason the gameobject would be surviving the destroy and just disabling the script that calls it along with a random collider ?
why can't i apply the object to the prefab?
Destroy(gameObject);
``` for that matter I am also calling this on the direct gameObject
prefabs cannot reference in-scene objects
https://unity.huh.how/references/prefabs-referencing-components
So, you loop through all child objects of this object's parent, then, if any of their parents have only one child destroy the parent? I don't really follow what this is doing, this seems like a really roundabout way to do if this object is the only child object of something, destroy that parent which is odd
If that's what you want to do there are better ways to do it
Yeah, that is all it's doing. I am currently just mocking up the final version it's pretty sloppy at the moment, but essentially I have a pooling system, that disables the script attached to inactive liquid in a "pool" to save resources, except instead of connecting pools it is just disabling the script on gameobjects leaving me with multiple pools that are empty anyways, it really doesn't make a whole lot of sense to why to me currently.
There's not really a reason why these shouldn't be destroyed, only occasionally they get destroyed which seems odd.
I think this might be happening because you mark a parent object for destruction, which also destroys all of its child objects, and then you change the child object's parent, effectivley "rescuing" it from the destroy
ahh, I see! That would actually make a lot of sense.
So, I think you should cache the current parent object, change the parent, then destroy the old parent
I guess I was assuming that the parent being "destroyed" wouldn't destroy the children.
I'll try that! And see if that works.
Actually, would swapping the Destroy and parent swap, just move the child and still have the old reference to destroy or do I need to fully cache it to a variable then empty it?
As it is know if you just swapped the lines all that would happen is you'd destroy the new parent object and everything on it
Yeah, that makes sense. I guess I'll just temporarily store a gameobject variable for the parent and destroy it afterwards, I doubt it's a meaningful performance loss anyway.
foreach (Transform child in transform.parent)
{
GameObject tempParent;
if(child.transform.parent.childCount == 1)
{
tempParent = child.transform.parent.gameObject;
child.transform.parent = GetLiquid(gameObject.transform.position, joinDirection).transform.parent;
Destroy(tempParent);
//child.GetComponent<LiquidScript>().isActive = false;
}
child.transform.parent = GetLiquid(gameObject.transform.position, joinDirection).transform.parent;
//child.GetComponent<LiquidScript>().isActive = false;
}
this worked!
Honestly the "parent" will have it's own script enabled on it which can selfdestruct when empty later on anyway, so even if it's sloppy it'll be changed later. I appreciate the help!
following a tutorial on converting meshes to terrain, it said to put the script in unity's editor folder in the project under assets, but i cant the editor folder?
You can't what the editor folder
Assuming you mean "find" the editor folder, it is a folder you make.
Just create a folder and call it (exactly, including capitalization) "Editor"
find 💀 mb, my brain is rotting
ty ty
i have a problem with a script and i dont know what the problem is
why are those hilighted red
What does the error say
Are you getting this error in the unity console or just the IDE
It seems like you have two classes named Mover that both have a function PrintInstructions
Oh, this is a different one. You have two PrintInstructions functions in one class
Do you have any other classes named Mover
in this script or in general?
Anywhere
Have you:
- saved the script
- restarted the editor
yes
i tried removing things and saving restarting saving and what not and its still showing all sorts in red
it was showing earlier the update and start as red
Try deleting your PrintInstructions function in this class. Is the line in start still showing an error?
No, keep the line in start. Remove the function entirely
You definitely have another mover class in your project
i dont know how tho
like if i do i have no idea how
You have public class Mover in a different file
okay
found the problem
here
there was another mover
but i have no idea how it appeared there
@polar acorn thank you tho for the time and effort i just was a bit blind
i have a timestop method that on collision changes Time.timeScale
i have a method that just plays a prefab with an animation on a button press
if i press the button when the timestop method plays my game permanently slows down, as if it never left the coroutine
they share no variables, objects, anything
has anyone had that happen to them?
Time.timeScale is static
show code if you need specific help, because all of this is just random pieces of your code. What coroutine? What does an animation have to do with this?
Ideally you shouldnt try to control the timescale from multiple places also, because of issues like this
apparently when you instantiate an object with an animation when the timescale is slowed down, the game will remain slowed until the next timescale update
i just hardcoded it to go back to 1.0 once i instantiate the object, but idunno how else one could do it
thank you a lot though!
Timescale only changes when you specifically change it. It doesn't go back to normal on its own
Could anyone help me with this problem? Ive been wanting to make the player who wields 2 guns have the guns allways point to where you are looking so that they allways look where you will hit. But when I have been using this script to try to make them face where the camera points, They are still rotating but not actually looking where I want them to look.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LookAtCursor : MonoBehaviour
{
public Camera mainCamera;
Ray ray;
RaycastHit hit;
void Start()
{
}
void Update()
{
Ray ray = mainCamera.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0));
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
Vector3 targetPoint = hit.point;
transform.LookAt(targetPoint);
}
}
}
I want the guns to be pointing directly at where the crosshair is showing
Place a small cube at the hit point and see if it's where you think it is else print/draw the ray and hit point.
I did try a debug.log and the position looked right
but i can try placing a cube to make sure
You should fix the errors from the top to bottom - the first error simply says you've got other errors.
For starters, it's suggesting that you're missing a directive or assembly reference
Ok can you explain what it means bro that why I sent it because i don’t understand what it means
What do I have to do to remove these errors
Yup cube goes where I want it to, not sure why the guns dont do the same
The code would have your guns look at the cube if those lines are processed
I have a rotating sun. It sets at (-1.5 X) and rises at (-1.5 X) because it goes all the way around. I need to switch the day/night bool each time it hits (-1.5 X)
if(sun.transform.eulerAngles.x == minX) {switch bool}
Doesnt really toggle, probably because it skips that exact value. How can I do this then?
Ok, I think i might need to redo my bullet spawning then because maybe that is the problem. I think I will do that on my own tho, Thanks for the help!
using a bit of logic you could check if it's day and past -1.5X or night and past -1.5X?
or if it goes from 1.5 to -1.5 you should just be able to check if it's past -1.5 entirely
might be easier with a visual though
If you're following a tutorial, you might want to double check that you've copied everything correctly. You've likely missed a step - the inclusion of the directive/namespace.
https://docs.unity3d.com/Packages/com.unity.ads@3.1/api/UnityEngine.Advertisements.IUnityAdsListener.html
Just like with Start earlier, you have another duplicate called OnUnityAdsDidFinish
I'm not certain how to explain it without simply writing/editing code - which is something I'm not willing to do.
so
if(day && xRot < 1.5f) switch to night
can you mockup a diagram as to where "-1.5" is?
- Sunset
- Sunrise
As you can see they are facing different directions but still are -1.5
(If thats what you mean? im not 100% sure what that sentence means)
how is it -1.5 at both angles? are you rotating the y axis to set the sun?
I was using local rotation, thats why I think. now its different which is good, give me some time to see if I can do it now
kk
What about for the IUnityAdsListener error
What could be the problem for that
I literally wrote the exact same thing
Can we get confirmation?
Your code above does not match this code
Oh, that is MoneyManager
Your errors are all in AdsManager
I've only seen the money manager script and not the ads manager script - not sure why it was shown rather than the ads manager script #💻┃code-beginner message
Did you save?
Yes
Clear the console
How do I do that
uhh, by hitting the clear button . . .
On mac btw
I works now:
float xRot = sunTrans.rotation.eulerAngles.x;
if (xRot >= sunriseAngle && xRot <= sunsetAngle)
{
day = true;
}
else day = false;
No difference error is still there
you can just say
day = xRot >= sunriseAngle && xRot <= sunsetAngle;
btw
Thats right, thanks
np
Maybe you're missing some setup with Unity Advertisements
How do I do that
Monetization of your Unity project through Unity Ads is a great way to generate revenue without charging your customers directly. A successful free ad-supported game will bring in many times the asking price of an ad-free game that must be purchased outright. In this tutorial, you’ll enable Unity Ads and implement an ad in your own project.
Share your updated 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.
what is the equivalent of
for (a,b) in zip(datA, datB) :
in unity
how does one do "zip" in unity
What language is that?
I'd assume it's a map of some sorts? If so, then C# equivalent is a dictionary.
providing the language would greatly help, that is true . . .
Looks like python? It's been a whiiiile, but they do the colon at the end of a for ?
i think its english
but i may be wrong.
It's definitely Python
anyway this is definitely not a Unity question at all, it's a C# question
but there's not really a direct equivalent for the (a, b) list comprehension deconstruction you've got there.
That's all python @rocky gulch
The real answer is step back and explain what your ultimate goal here is, because the Python way of doing things:
- Isn't going to work directly in C#
- Is likely not very efficient in a game
!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.
And !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
You should be able to see the compile errors in the ide
you used a thing that doesn't exist
How do I make it exist
Either you don't have the ads package installed, or you're following examples or tutorials for a different version of the package than the one you installed
so either:
- install the thing you didn't install
or - Find tutorials or examples for the thing you did
To add to that:
The tutorial probably covers the required dependencies and how to install them
It not really a tutorial my college gave it to me for a assignment

