#💻┃code-beginner
1 messages · Page 246 of 1
Idk, check that you have the correct version for your tutorial (?)
Oh, I didn't know. Thanks for explaining!
its different version but i did switch the the oldd version too but still it wont let me do it
And he did have a forum explaning about it and i did the exact thing
still wont work
What does IL means btw?
Interpreted Language. It's a cross platform kind of assembler that C# compiles into
https://docs.unity3d.com/Packages/com.unity.xr.arfoundation@4.1/api/UnityEngine.XR.ARFoundation.ARRaycastManager.html
It exists in the documentation
can somone expalin why my code is red
im trynna create abilities for health and speed
Did you read the error?
wowuld it be better if i create 2 diffrent scrip instead
these are the only packages i go
oh cause i already have player so shall i create another script for health
nvmm
You can't have two variables with the same name.
Ok thanks. And do colliders work even if the target is already inside the collider? For example, I want my ai to shoot if the target is at 10 meters. So I make a 10m sphere collider around my AI. But what if the player spawns inside the sphere for some reason. Would the collision still trigger at least once?
That should have it. You have AR foundation 5.1.2.
Go to the gameobject, hit Add Component in the inspector and search for the ar raycast manager
OnColliderStay()
yes, it will fire
or rather OnTriggerStay() for your use case (I think)
Ok thanks!
OnCollisionEnter or OnTriggerEnter will fire on Instantiate
Ok, I think I did read it should be a trigger in this case indeed.
OHHH it worked 😭
Thanks a tonn ! ive been trying to fix this for like 9hrs noww
Ok. I'll have to think of the case where target player escape so AI need to check if there is another player maybe already inside his collider. Sneaky players lol
Learning the basics of unity would help lol
ConfigurableJoint = my brain hurty lol.
I should i should
Its just we are suppose to make an application and our proposal had be done though unity
anyways thanks a lot man
Use Slerp drive mode, adjust slerp drive's max force etc. Then update the joint's targetrotation from script
Might be something I cant remember rn but that should do it 🤔
Yeah I'm just reading through the docs atm and figuring it out. Never used Physics joints before, so know nothing about how they work. lol.
Joints can be, hmmm, 'tricky'. I tend to implement them in a test project to get the behaviour right before trying to integrate them into my main game
Yeah I'm working in my 'test scene' atm trying to get this to work. lol.
how do i pick a random item from the items[] array, with weights?(weighted randomization)
[System.Serializable]
public class CrateItem
{
public GameObject item;
public float probability = 0.5f;
}
[CreateAssetMenu(menuName = "DELTA-V/Supply Crate config")]
public class SupplyCrate_cfg : ScriptableObject
{
public Vector2Int numberOfItems = new Vector2Int(2, 3);
public CrateItem[] items;
}
Well by jove, I think I cracked it. lol. No need to update the rotation etc.
I'm struggling to make an inventory system for a while now. I'd like to identify my items with string id's for storing in the gamestate. How should I associate some item codename with an in game item, and an inventory representation. Say I read from the gamestate that the player holds a "key1". I'm thinking of some inventorymanager gameobject (prefab and/or singleton) that will hold a mapping of key1 to a prefab I can instantiate when reading the game state. If I can load an arbitrary prefab like that, what are resources/load for?
Every inventory system that I've seen from recent years have been Scriptable Object based (still a bit baffled by them myself tbh), but there are some good tutorials/guides on YT on how to implement them etc.
yo lads im actually tweaking
why is void red bro
all I did was add the bird reference and now void is red when it worked before
ive looked online but it said about some guy having a similar issue but his code was correct, and all he had to do was reinstall vistual studio
i dont think that is the case with me
Check the syntax on AndroidJavaRunnable (never seen that before myself, so dunno what the syntax supposed to be)
because line 9 makes no sense
yeah i did look at that and thought that it was a bit odd, however i was following a Unity tutorial so i thought that line of code was necessary for something and I just forgot why i needed it in the first place
i just noticed that line 9 is yellow so i must have changed something there. Ill try deleting it to see if that makes it work
I very much doubt if any tutorial (apart from one telling you how not to do things) would have a line of code like that
maybe i just accidently clicekd tabbed or something, im not sure
you are the programmer, you bloody well should be sure of what you are doing
well I don't know how that line of code appeared there, so I can't tell you for certain
anyways I deleted that line of code and it all seems to work well
a great unity totorial once you are finished that one is https://learn.unity.com/course/create-with-code?uv=2022.3
In this official course from Unity, you will learn to Create with Code as you program your own exciting projects from scratch in C#. As you iterate with prototypes, tackle programming challenges, complete quizzes, and develop your own personal project, you will transform from an absolute beginner to a capable Unity developer. By the end of the c...
thank you
is that 3d is it
for inventory systems, is it best to use ScriptableObjects or Interfaces?
if so that would be great because i wanted to make some 3d skibi toilet game thats why i started learning unity 💀
i just read it, it is 3d, thank you ill check it out
I have a prefab in my project that is calling OnValidate on itself, and null referencing because a bunch of its parameters are null
Except that prefab isn't in my scene anywhere, and there are no references to that prefab, and the only instance of that prefab has all its values set
How can this possibly be happening? How can I debug why this is occuring?
I do not understand why this is even physically possible that its occuring because it physically does not exist anywhere so its not physically possible that its happening, and the visual studio debugging is too garbage to tell me EXACTLY where this impossible call is coming from
How do I debug this?
Like here it is sitting on a code hook, calling the method
except it wont tell me where/what/when/how this thing is
this thing that is calling this code that cannot exist, where is it and how do I kill it
I tried to debug its 'name' but that didnt help me find it
Ill try what you suggest now
you will get a message in the console
after you click on it
it will show you what object called the debug.log
gotta love some one who is so sure about everything except bloody obvious logic
When I click on 'on validate' in the console, nothing happens, there is nothing selected
im asking for help, not for you to be an asshole, please keep your snark to yourself
The only thing in life I'm always unsure about is whether or not my burrito is still cold in the middle after I microwave it 
it will highlight the object on the scene that is calling it
in the hierarchy
Yes Im saying nothing is highlighted
I click on the error and nothing in highearchy highlights, nothing selects, nothing occurs
well perhaps you might phrase your question in a much less obnoxious way then
i didint ask you to click on the error
"you will get a message in the console
after you click on it"
yup
Define "it"
"i didint ask you to click on the error"
is the console field not 'the error'
What is the is
lol
What am I supposed to be clicking on
why are you laughing at me, I am asking completely clear questions and you are giving me run around
The onValidate one
Just tell me clearlyt exactly what I am supposed to click on, not 'It', I clicked on 'Onvalidate' in the console, and nothing in the hiearchy gets selected
Yes, I did that, I clicked on that
Like I said, already, I clicked that, and nothing occured
reported for verbal harrassment, blocked
what lmao
It highlights as soon as it is selected. Switch away from it to another line then click again to see highlight
I don't know how I can make this more painfully clear when I say nothing is selected, nothing is being selected
I can click on 'onValidate', and nothing in hierarchy is selected
There is no selection occuring, no highlighting
because you just did Debug.Log("onValidate");
I did exactly what you told me to do
I copied your code directly
Super weird, just tested on my end and it works in that function (assumed maybe it was blocking somehow)
I really don't appreciate being treated like a stupid idiot when I am doing exactly what I am told and then gaslit when I am doing exactly what you told me to do and its not doing what you expect it to do
reported for verbal harrassment
Error could have halted highlighting behavior
comment out the rest of the OnValidate function
leave just the debug.log
Can also put the object in the LogError as well (also supports that). Although it should be working already in the normal log itself 🤔
Just the debug, shows up twice in console, clicking the console messages (either) highlights nothing in hierarchy
the heck
debug the gameObject.name
and show the result
then search the hierarchy by that printed name
I am glad that you think this is crazy because it validates my feeling that this shouldn't be possible
and makes no sense
also open Project tab, next to your console
will do
yes, if this game object is coming from an asset, the context will take you to the project window
click on the onValidate
and see if any file from Project tab
is being higlihted
Yeah check the project panel
move it to the side so you see both windows at the same time
OnValidate will fire for prefabs on script reload
Okay we're getting somewhere, I have console and project on the same tab so I wasnt seeing project change
Its selecting prefabs in the project, two separate ones.

OnValidate isn't only called on instances, but also on prefabs
My new question is: How can OnValidate get called on a project prefab? I thought it only gets called on things in scene?
onvalidate is for when inspector values change, isnt it?
no
It's more general than that.
did you read the OnValidate docs
it does lead with
Editor-only function that Unity calls when the script is loaded or a value changes in the Inspector.
but this isn't exhaustive
Yeah so the first part is this case for example
actually, what is "script" here? I presume it means "when the instance is created"
Are you asking me? The script here is ```public class InitiativeEntry : MonoBehaviour
No, I'm looking at the doc line I quoted
Oh 'the script' from the doc
the documentation likes to say "script" when it doesn't mean "script"
the scary part is that OnValidate can run on threads other than the main thread
@swift crag near the end
which results in mysterious behavior if you try to interact with the rest of Unity's API
ooh, I should give that page a read
ye, cool chart
also, I keep my project and console window separate for this reason (well, and because i have an ultrawide screen)
what is the best way to learn unity?
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
So here is what it looks like was happening
In my project I had two separate prefabs called 'InitativeEntry'
in my scene I had a script referencing one of them
the one being referend had all of its parameters set, there was nothing null on it
But somehow both prefabs were being OnValidate called even though one of the two was not the one referenced in scene
Thats not how inspector dragged in references / GUIDs work to my understanding
yo this is handy! and it reminds me that it took me years to figure out what the hell a ctor was...I thought everyone was misstyping 'actor' or something
and I am 100% sure I had the correct prefab set because double clicking it took me to the prefab which showed me all the values were not null
But 'onValidate' was being called twice so both were being called
Thats not how unity works to my understanding, does someone who knows more than me make sense of that?
I would not be surprised if the second prefab was still loaded by the editor
yep i think onvalidate gets called by the editor and doesn't care if the thing is in the scene or not
I am not familiar with exactly what situations OnValidate can run in
I was going to say that I bet this wouldn't happen in the build
...but OnValidate doesn't run in builds at all
so there you go
Yeah thats why I thought OnValidate only got called in Inspector when variables change, in unity editor itself since thats the only place where there is an inspector 
Yeah when your domain reloads (play mode or just normal script changes) it will run all of the onvalidates in the scene and on prefabs/SOs (near the end on the chart above).
I can't type properly omg
You should write OnValidate code very defensively, since it could be running on things you haven't finished configuring yet
(and since it might not even be running on the main thread)
It gets called on load and on build (like, the build pipeline in editor, not when running a build... perhaps as part of the load thing), but I can't quite say when exactly is it called... definitely more than just changing the thing in the inspector though
Good to know 
at work we add some code to all OnValidates to make sure they don't execute at play mode in the editor, to align play mode better with builds... before that we had random errors in builds only, because the OnValidate would run in the editor and automagically resolve and hide the error 😒
the docs do kinda suggest that OnValidate is called from all kinds of random places (without explicitly specifying them 😄 ) https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnValidate.html
so far, I've only really used OnValidate to copy an asset's GUID into a field on a component
I have this code here in the picture below, infoLight and the other one are both from the same prefab that I've added to the gameObject twice. Other methods in the same class simply use _infoLightMaterial.SetVector to define a color.
Weird issue though, I'm a 100% everything in the code is correct BUT _maintenanceLightMaterial can be modified and will appear in-game, _infoLightMaterial will NOT WORK, workaround is to just do infoLight.GetComponent<Renderer>().material (again).SetVector.. any idea what could cause this behaviour?
When you access .material, you get a copy of the material unique to the renderer
When you access it for a second time, it won't make a new copy (since it already has a copy)
however, that shouldn't cause this to break
I use it all the time to debug code that sets to fields functions as a quick way to edit the field and see results. Eg like I want to test if X method does Y from inspector without calling X method, I just onvalidate and change the value directly
but yeah only good for debugging, not meant for actual build
So when I call .material, it assigns a new material (copy) to that renderer?
Can you share the entire script?
Sure!
Correct, and material will then return the copy
sharedMaterial doesn't make a unique copy
@swift crag
public class EmissiveLightController : MonoBehaviour {
private const string EMISSION_COLOR = "_EmissionColor";
private static readonly int EmissionColor = Shader.PropertyToID(EMISSION_COLOR);
[SerializeField] private GameObject maintenanceLight;
[SerializeField] private GameObject infoLight;
private Material _maintenanceLightMaterial;
private Material _infoLightMaterial;
private Color _infoLightInitialColor;
private void Awake() {
}
private void Start() {
_maintenanceLightMaterial = maintenanceLight.GetComponent<Renderer>().material;
_infoLightMaterial = infoLight.GetComponent<Renderer>().material;
_infoLightInitialColor = _infoLightMaterial.color;
}
public void UpdateMaintenanceLightColor(float maintenanceLevel) {
var percentageAsColor = ColorsUtility.PercentageToColorGPT(
GetComponentInParent<TowerController>().GetMaintenanceLevel(),
new List<Color>() {
GameTheme.positiveColor,
GameThemeRTR.FlowColor,
GameTheme.negativeColor
}
);
_maintenanceLightMaterial.SetVector(
EmissionColor,
ColorsUtility.ConvertToHDR(percentageAsColor, 4f)
);
}
public void ShowMiss() {
_infoLightMaterial.SetVector(
EmissionColor,
ColorsUtility.ConvertToHDR(GameTheme.negativeColor, 6f)
);
//infoLight.SetActive(true);
StartCoroutine(ResetInfoLight());
}
private IEnumerator ResetInfoLight() {
yield return new WaitForSeconds(0.5f);
//infoLight.SetActive(false);
_infoLightMaterial.color = _infoLightInitialColor;
}
}```
does infoLight have more than one renderer on it ?
I would suggest referencing it as a Renderer instead of as a GameObject
so that the GetComponent<Renderer>() can be removed
I've gotten footgunned by this before
I wound up getting the wrong renderer and breaking it
Will try referencing the renderer directly and let you know, seems like there's only one renderer but you're right that it's just better to target it directly
@swift crag Same behaviour
Clicking on Light will indeed show it points to obj1 child2 and second one obj2 child2
so they do seem to point at the right thing
with the mystery of one behaving differently than the other, and those not being affected by other scripts either
Serialize _infoLightMaterial so that we can look at it in the inspector
(and do the same for the mainenance light material)
okay
You can double click on the material to inspect it, even though it doesn't come from an asset
you can see if its colors are changing properly
omg i get it now
thanks a lot, basically when i place the building there's a material that's changed
Hey again, so I have my ship controller sorted, beyond a few number tweaks. Now I'm trying to get a 'smooth camera follow' script working, but for the life of me I can't seem to get the camera to rotate on the Y (Up) axis and it's driving me nuts.
Initially I was using LookAt for the camera to point at an empty at the front of the ship, but the Camera kept 'banking', so I changed it to enter the values directly based on the rotation of the ship. But it just refuses to rotate.
Could anyone please point out where I'm being an idiot please?
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.
eagleRoot.rotation.z
This is not a meaningful value
this is the Z component of the quaternion vector
You probably wanted eagleRoot.eulerAngles.z
Ah bugger, yeah probably. Thanks. Will give it a go.
wtf? Okay, this is really bloody confusing me now. The ship rotates on it's Z axis. I get that value and apply it to the camera's Y axis, but the camera rotates on its Z Axis.
share the updated script
!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()
{
Vector3 desiredPosition = positionTarget.position + offset;
Vector3 smoothedPosition = Vector3.SmoothDamp(transform.position, desiredPosition, ref velocity, smoothSpeed);
transform.position = smoothedPosition;
Vector3 rotationVector = new Vector3(-65, eagleRoot.eulerAngles.z, 0);
transform.localRotation = Quaternion.Euler(rotationVector);
}
the camera is only rotating on its X axis in this image
and the ship has zero rotation around the Z axis, so you get zero rotation around the camera's Y axis
No, it rotates on the Z axis. The X and Z supposed to be locked (the two images are showing the 'orientation' of the ship (first image) and camera (Second image)
It's rotating around its X axis.
The blue arrow moves as a result, yes
but the rotation is purely around the X axis
No. The two images are two seperate things selected. The rotation is locked more or less at -65 on the X axis.
When in game mode, the blue arrow doesn't move at all, it stays pointing forward. 1 sec
Neither image shows anything being rotated around its Z axis, so I don't understand what you're talking about
Thos are just the orientation of the two objects (Ship and Camera) and why I'm getting the Z reotation from the ship and applying it to the Y rotation of the camera.
That's what happens though.
I believe rotations are applied in the Z -> X -> Y order, so an X rotation occurs before the Y rotation, and you get the weird apparent roll
Try doing this
Quaternion.AngleAxis(eagleRoot.eulerAngles.z, Vector3.up) * Quaternion.AngleAxis(-65, Vector3.right)
this is how I compute a first-person camera's rotation based on yaw and pitch angles
um can someone help me with unity ?
Does exactly the same thing. 😕 I really don't get why it's applying the rotation to the Z axis even though I'm telling it to apply it only to the Y. 😕
actually, I don't think your camera is rolling at all here
The green up-arrow would be tilting to the side if that was the case
you're looking left and right at a big sphere
that's going to look like you're tipping the camera over
my bad for interrupting but i been looking for the unity preference so i write in the script but i actually can’t find it and nothing is helping… if anyone can help 🙏
let me show me then
ooh, there it is, okay
Driving me nuts. lol.
first, to sanity-check this, what happens if you just copy the rotation of the ship?
basically it will allow me to edit(write) inside for my component script
you don't edit your script inside unity
you use a code editor
you should follow a course on !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
it will teach you how to use the editor
(also, did you switch back to using Quaternion.Euler ?)
i'm going to see if i can recreate your problem
Hold please. lol.
Okay, so just copying the rotation of the ship using
transform.rotation = eagleRoot.rotation;
the camera behaves exactly as expected (it points 'down' and rotates the same as the ship)
thank you man 🙏
do you just want to get an offset from the ship's current rotation?
using its world Z euler angle for your own Y euler angle is kind of odd
Ship Orientation
Rotates Left/Right around it's Z Axis and it always pointed to the center of the moon.
rb.AddForce(Vector2.down * recoilForce);
how do I make this line of code have Vector2.down be relative to a referenced Transform
transform.down will give you the Transform's "down" direction
you can also do transform.TransformDirection(Vector2.down) to get the same thing
it'll give you a Vector3 back, but that will implicitly convert back to a Vector2
Maybe you want to use its local Z rotation, then
since you're using its world Z rotation
However, if you just want to get an offset from the ship's current rotation, that's easy to do
Quaternion.AngleAxis(65, ship.right) * ship.rotation;
e.g.
I've tried 'localEulerAngles.z' and it didn't change anything. 😕
this will rotate the camera by 65 degrees around the ship's right-vector
I don't like to work with Euler angles directly, really. They just cause headaches.
It's just supposed to be a simple 'follow cam' script. It follows fine, it just won't bloody rotate. Even tried cinemachine but nothing. 😕
you'll have a similar problem on the camera -- as the ship moves around the world, the axis you want to rotate around will be constantly changing
yes, you're assigning to localRotation, but the camera has no parent
so that's just world rotation anyway
If you ask, then maybe
Woah, massive lag... sorry
This will behave correctly at all times
when you directly construct Euler angles, you tend to get something that only works in a specific orientation / when you're aligned to an axis
Okay, I'll have a read and see if I can get it work. Rotations alway, without fail trip me up.
Sticking to quaternion methods and multiplication makes a lot of those problems go away
i try to design my code to work in all situations, including ones I haven't thought of yet (:
Okay, sorry to bug you again, but yes, this works (camera rotates on the correct axis).
transform.rotation = Quaternion.AngleAxis(eagleRoot.eulerAngles.z, transform.up);
but, now I need to set the X and Z Axes and struggling to find the answer. 😕
Does this not do what you want?
Also, this isn’t really stable. You’re computing a rotation based on your own rotation!
Hmm? Howso? Sorry, don't really understand, I'm basically 'copying' the rotation of the ship to the camera.
Just swtiching an Axis.
You’re using your own up direction to compare the rotation, so this depends on your current rotation
Also, why are you trying to “switch an axis” in the first place? That sounds weird
please give this a try
Because the ship rotates around it's Z Axis, and the camera needs to rotate around its Y Axis the same amount that the ship is rotating around it's Z Axis.
Okay, yeah sorry that worked. I might a typo cockup when I tried it first time round. My bad.
It's working as expected now, thank you. Really appreciate your help (And Patience. lol.)
A rule of thumb is that, unless you’re working with local rotations, you shouldn’t be directly constructing euler angles
it breaks once you’re no longer aligned with an axis
and good!
You can adjust the angle to change the amount of tilt
Yeah, already got that bit variabled up. lol.
So i have a playermovement script using rig2d.addforce but the longer i hold the faster it goes and i was wondering how to cap the speed?
Use ForceMode.Acceration I think it is.
Maybe Impulse? (not massively conversant on the different types tbh.
Can I use Animator/Animation for UI as well? Or is it designed for regular GameObjects and there's a different system for UI
Yes you can.
Changing the force mode just changes how much velocity change happens
It won't help you get a maximum speed
for all of these examples, assume the object weighs 10kg and that we're passing Vector3.forward to AddForce
When I use the Sprites in UI Animations they are extremely small (obviously). What's the best approach to make them bigger?
Might be best asking in https://discord.com/channels/489222168727519232/502171135350407168
ForceMode.Force is a continuous force that cares about mass. If we call it for an entire second, the object's velocity goes up by 0.1
ForceMode.Impulse is an instantaneous force that cares about mass. If we call it once, the object's velocity goes up by 0.1
ForceMode.Acceleration is a continuous force that doesn't care about mass. If we call it for an entire second, the object's velocity goes up by 1
ForceMode.VelocityChange is an instantaneous force that doesn't care about mass. If we call it once, the object's velocity goes up by 1
Use Impulse and VelocityChange for things like jumping
Use Force and Acceleration for stuff that happens over time, like driving a car
anyway, to limit the maximum velocity, you have a couple of options
The most obvious choice is to just clamp it
yes thats what i did and it works great for jumping but not side to side movemeny
rb.velocity = Vector3.ClampMagnitude(rb.velocity, maxSpeed);
run this in FixedUpdate
note that this won't perfectly clamp your velocity
This runs before the physics simulation, so the object can get accelerated after you've clamped the velocity
But you'll be clamping it every physics update, so it'll be pretty close
Another option is to reduce the amount of force you can add if you're going too fast
float forwardSpeed = Vector3.Project(rb.velocity, transform.forward).magnitude;
float power = Mathf.InverseLerp(maxSpeed, maxSpeed * 0.9f, forwardSpeed);
rb.AddForce(power * transform.forward);
At maxSpeed, you get 0 power
at 0.9 speed, power is 1
you'd probably want to do power * accelerationForce !
where accelerationForce is the maximum possible force the car can apply
To get something physically accurate, you shouldn't mess with the force at all
instead, apply drag
wait for clamping how do i set in a specific number ?
oops, i forgot the second argument
just fixed it
rigidbodies have a "drag" field, but it's not really physically accurate. it's not like air drag
thank you and would it work the same for 2d
a feather gets affected by drag just as much as a hammer
I'm not sure about 2D, actually. Maybe drag works differently there.
But if you want to do drag yourself, it's pretty simple
rb.AddForce(-rb.velocity.normalized * Mathf.Power(rb.velocity.magnitude, 2) * dragCoefficient);
air drag is proportional to the square of your speed
Your maximum speed is the point where air drag gets more powerful than your engine
IT WORKS
wait
I added the cap which works great for side to side but now my jump is capped and it barley jumps
If you're capping the velocity, consider only doing it horizontally
Vector2 velocity = rb.velocity;
velocity.x = Mathf.Clamp(velocity.x, -maxSpeed, maxSpeed);
rb.velocity = velocity;
This won't touch the Y value.
thank you it worked
Does anyone know if there are any settings to make long lines wrap in Visual Studio?
Just working on an .xml file with some very long blocks of text and I'm wondering if I can improve readability somehow
Yes from the options. Tools > Options > Text Editor > [your specific language / All Languages] > General, Word Wrap
goat
You can always do float targetvel = Speed - RB.velocity.magnitude; and then multiple your movement axis by it 🤷 (This does introduce some bugs though I'm pretty sure)
with this code that ive used
there always 1 heart left showing
even thought the player dead
is 0 < 0 true or false?
pretty sure if checks are slower than just doing Mathf.Clamp(health, 0, maxHealth); for your health clamp
That's false because 0 = 0
since 0 cannot be greater than 0
Can someone help me please
When I view the vfx it looks fine but when running the car it just speeds up drastically
but that depends on is it an int or a float
Sorry for bad quality
right, i was posing the question to Mirage :p
with a float it might be true or even false
if two floats are both exactly 0, it'll always be false
Floating point errors exist but I'm unsure since I never tried checking is float 0 greater than float 0
nah the check isnt slow the charachter dead and it shows 1 heart left
"floating point errors" don't mean that 0 > 0 :p
this is not the way floating point error manifests
ah, you destroy the game object when your health hits 0
floating point errors could mean that 0 is actually 0.0000001 or anything close to that really
i don't think the script is getting a chance to update your health display
0 is 0
shall i remove = sighn
now if you did a calculation that should end up with 0 it might end up being slightly not zero
Okay well, too lazy to explain floats to you by now so I'll be going now
but if you type (0f < 0f) it will be false
Move the health bar code into another function
Call that function after you take damage and in Update
it's fine to not know something, but you're just being confidently incorrect here
Please tell the solution
Not a code question
if you don't understand something, don't try to lecture us about it
I mentioned floating point errors which do exist, and I did mention that I never tried out 0f < 0f so I am not implying that I am correct
i removed the equal siggn no it the charchter still alive when 0 hearts are showing
Keep that as it was.
health <= 0 is the correct condition for being dead.
Do this.
Destroying the game object means that Update doesn't get to run anymore
(because the object and all of its components are gone)
how do i move it into another function 😅
i thought it was already seprated
void Update() {
DoHealthbar();
// other stuff that happens every frame
}
void Damage() {
// reduce your health here
DoHealthbar();
}
void DoHealthbar() {
// code that updates the health display
}
isnt mine like that ?
No. You have all of your healthbar code in Update.
Move it out of Update and into another method.
cant i just replace the word update
no, because then you won't have an Update method being called every frame
do you not understand what Update does?
that will work. It's only really important in TakeDamage, since IncreaseHealth won't destroy your game object
so i can remove updatehealthbar out of that function
yes, that will be fine
to clarify what i did is that i took the healthbar out of the function and put it in a new one then we continually update it?
The healthbar code used to be in Update.
This meant that it ran once every frame.
You moved the code into a new function. That function is called from Update, so it still runs once every frame.
You also call that function from TakeDamage. This makes sure that the healthbar updates even if you die.
oh ok thx before it didnt update cause it didnt update as the objext was destroyed?
Right.
Your PlayerHealth component was destroyed when you destroyed gameObject (since destroying a game object also destroys all of its components)
ok thanks alot that was helpful
how do i convert a number between 0 and 1.6 to 0 to 1, this is for the purposes of a lerp function
@final trellis x / 1.6
thanks! google results were significantly more complex than that lol
For weirder ranges you can use an Mathf.InverseLerp(min, max, value)
why is smoothdamp so framerate dependent?
like when my game is in windowed mode the smoothdamp is soooo slow
and when im in fullscreen it runs at god speed
transform.position = Vector3.SmoothDamp(transform.position, ladder.cancelPosition.position, ref ladderPositionVelocity, climbCancelPositionDuration * Time.deltaTime);```
is it because i multiply by Time.deltaTime?
i removed it and it didnt fix the issue
anyone?
Do someone want to help me create a 3,2,1 GO countdown for my game?
using deltaTime is wrong
it will fix the issue; you probably just didn't recompile or something
does this goes for smooth damp as well?
it was still there
no, because SmoothDamp does not work like Lerp at all
im not sure whether this is a coding issue but objects look very blurry when i move and turn
read the documentation for SmoothDamp.
It does have a deltaTime argument, but it defaults to Time.deltaTime, so you don't need to pass anything there
transform.position = Vector3.SmoothDamp(transform.position, position, ref ladderPositionVelocity, ladderStartPositionDuration);
its still slower when in full screen
You probably have incorrect logic somewhere else
this is the logic
how do you calculate position ?
Vector3 position = new Vector3(ladder.bottomStartPosition.position.x, ladder.bottomStartPosition.position.y, ladder.bottomStartPosition.position.z);
wait i dont need that anyways
and then how do you change the target position?
ah, you're using it to attach to the ladder, not to move up the ladder
yeah
but moving up the ladder is also broken
works slower and faster
depending if ur fullscreened
share the entire script?
the whole script is 2000 lines
btw its not just this smoothdamp
this is running slower in windowed
landingHeight.localPosition = Vector3.SmoothDamp(landingHeight.localPosition, Vector3.zero, ref landingVelocity, landingCameraUpDuration * Time.deltaTime);
and faster in fullscreen
so you basically made a Game.cs
that's not good
not really
ever heard of single-responsibility rule?
just movement script
with probably 30 if/else statements?
not at all
yes, you never use deltaTime to calculate the smoothTime parameter
been making this for 2 months
read the documentation
Approximately the time it will take to reach the target. A smaller value will reach the target faster.
You don't just mash deltaTime into random places
i mean yeah i forgot about that Time.deltaTime
but without it it'll do the same thing
like with the ladders
there may be slight differences depending on framerate, especially as you get really close to the target
is it cause im directly setting it?
landingHeight.localPosition = Vector3.SmoothDamp(landingHeight.localPosition, Vector3.zero, ref landingVelocity, landingCameraUpDuration);
instead of likeVector3 targetPosition = Vector3.SmoothDamp(landingHeight.localPosition, Vector3.zero, ref landingVelocity, landingCameraUpDuration); landingHeight.localPosition = targetPosition;
no, that isn't relevant
no, it is not relevant. there is literally no difference.
it doesn't matter what your unity version is
does the component Nav Mesh Agent no longer exist?
It does exist still
Im trying to add the component to my object but I cant find anything under nav or navigation?
Do you have the AI package installed?
It is now part of a package iirc
is it possible that its not the smoothdamp thats affected by fps/windowed or fullscreen and in fact its the coroutine?
i think it might be that
How do I make a Topdown 2D Enemy AI that can only move in 4-directions without it being janky?
I had an old Enemy AI that allowed them to move Diagonally but I've restricted my Player to only move in 4 Directions (Because I have a D-Pad set up), so allowing Enemies to move diagonally wouldn't really be optimal.
When I restrict my enemy's movement AI to 4 directions, it starts tweaking out towards the player when they're in aggro range
Can you post your code?
yeah without seeing your code there's not much we can do
Ah give me a second then. I have to pull the 4-directional one from my old project
so generally how much should i study the unity docs for programming?
What do you mean study docs? Like are you just looking at random stuff in the docs?
looking at docs for trying to find solutions to problems, not really knowing what to do
Well, for those specific three, after the movement code executes, do some checks. If the player’s velocity is low/zero, then do idle. If they’re in the air, do jumping. If their horizontal velocity is more than zero, then do walking.
That’s the general idea at least
First off, do you know c#?
not really, most of my coding knowledge is python, but i know the basics id say
Well, starting off, learn some c#
you don't study them. They're reference materials you look at as needed.
C# and Python are quite different.
i mean, i know the basics of c#, but i know a bit more about python
Hello, I'm somewhat new to unity, working on a few simple game projects. I'm a programmer at my day job so I'm pretty familiar with programming in general. I know in a lot of unity tutorials they use a game manager singleton to manage things like game state such as scene management, player score, game over, etc. I've seen some people call this bad practice online, my question is, what is the alternative? I can't really imagine how else you would manage game logic like that? Would you have a separate script for scene management, then one for player score, etc?
Kinda depends on your definition of “the basics”, are the issues you’re running into c# or unity related?
mostly c# related
I don’t know why that would be bad practice, I’d say use a single ton game manager to handle stuff like scenes and game states, and then scene managers to handle in scene stuff that a singleton shouldn’t really need to handle
Well, how about this, what issue are you currently running into?
its not about an issue im currently on, im just looking for ways to improve at scripting
Learn C# outside of Unity first
For example, a game manager singleton doesn’t really need to know if the player is crouching or not, as that doesn’t really affect anything outside the current scene. A scene manager doesn’t really need to know that either, as the only thing in the scene that affects is the player, nothing else. So, you’d put that logic in a script attatched to the player.
Does that make sense? I could use your specific case as an example if it doesn’t.
Separation of concerns into separate scripts of course yes.
so about how good at c# should I be before I can sort-of decently program in unity on my own?
like when would be a good point to call the training wheels officially off
There’s no real measurement of c# skill. I’d say just do like the codecademy c# beginner course and that’ll probably give you enough info
I think it makes sense, what would a SceneManager need to know though for example?
i took a game development course last year where i made a game in unity with a little help, so im not exactly a complete beginner
if you don't get confused by the syntax, you might be good enough.. you'll need to read up on new stuff you encounter, of course... and learn the Unity side of things
Oh sorry I just noticed you said an example from my specific case. Anything I've worked on so far just has one scene, so honestly I'd imagine I don't need to worry about this until I start working on more complicated projects? Like let's say a basic game with title screen, game scene, and game over screen, that could all probably just be managed in gamemanager right? With score, health, etc. deciding whether to show gameover screen
This is a pretty specific example but I can’t think of much else at the moment, have you seen that one stick fight game?
I think I know what youre talking about, never played it though
Looks like there's different stages that are scenes? Is that where you're going with this?
{
if (other.gameObject.tag == "Obstacle")
{
SceneManager.LoadScene("Game");
src.clip = deathSound;
src.Play();
Debug.Log("Sound");
}
}```
Hello! Can anyone let me know why this sound isn't playing? I tried putting it somewhere else in my code just to see if I set it up correctly and it worked, but this is where I check when the player dies, the "Sound" gets logged to console
you're loading a new scene
Well, it basically consists of rounds, where players fight each other until the last one is standing. There are multiple different types of rounds, like a statistics round, as well as the menu and stuff. The game manager would control switching between these scenes. The logic that would consist of detecting when there is only one player left standing would be handled by the scene manager. Lastly, player movement would be handled by a script attatched to each individual player.
Which means the audio source is going to be destroyed. @abstract onyx
do what
play the sound on death before the new scene gets loaded
Don't load the new scene until the sound is done playing
Also use CompareTag instead of equality
I see, so the scene manager would tell the game manager when one player is left standing and that it should switch scenes then correct?
oh I see, let me try, thanks again!
Yes, it varies game to game, esp depending on how complicated your game is, but that’s the general idea
how can i fix smoothdamp running faster at lower fps?
Alright thanks, I think I have a better idea of it now
Its been a while but I followed it and it worked, so thanks
Sorry for the wait. This is my script:
!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.
Basically, it works fine when the player is still far away but if the enemy is getting closer and the player is at an angle (Not directly in front/behind or to the side of them), it will start zigzagging between Horizontal and Vertical
mb, i'll throw it in there
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.
I like coding but idk what to code that will be fun
Well, it's gonna zigzag if you make it look for the shortest path as you do now.
You'd either need to use some kind of pathfinding solution(like a*) or prefer one axis over the other and only make it switch the direction when it's not possible to move closer on the preferred axis.
Ah I've tried A* Pathfinding but I couldn't figure out how to set it to 4-directions only
Read the documentation
You could always start with something you’re unfamiliar with. For example I plan to make a sandbox of game objects to just experiment with the physics system to better understand it. And maybe something cool will come of it
is this outdated? didnt have this error last night
Why are you using GraphView
actually idk how it got there thinking about it now
Then remove it?
Also, if your IDE isn't underlining errors in red you need to configure it !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
it is configured but that error isn't getting underlined
it only shows it when building the project
You can't use UnityEditor code in a build, so that's why that occurs
Same problem.
Hey, so if I attach multiple enemy scriptable objects to a script, what's the best way to swap between these objects?
What happens here if combo is currently == 2?
if (combo < 3)
{
combo++;
}
Depends on your code...
That's true, I just didn't find any easy ways on a quick google search. Would a if statment work for this?
What multiplier do you guys ussually use when using rb.velocity with Time.deltaTime? What number is the multipler I mean* cs void Update(){ rb.velocity = new Vector2(rb.velocity.x, jumpForce * multiplier * Time.deltaTime); }
Probably..? An if statement doesn't exactly explain what you're trying to do.
You shouldn't use delta time with velocity.🤔
What do you mean? What is wrong with it?
Well, imagine you're driving a car in real life and your velocity goes up and down +-5 km/h every few milliseconds without apparent reason.
That's also true, sorry. I meant like in the script that I attach the object to, if I use an if statement to see if a boss is dead and then swap to a new boss when that is the case.
Sure you can do that. Again, I can't say anything specific without seeing the code.
If I don't use it other pc's will have a different speed, wont it?
No.
Velocity is used by the physics system and is multiplied by the fixed delta time before moving the object.
!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.
Okay, that makes sense. Thank you. However, what is the multiplier number that you recommend when use Time.deltaTime?
I don't understand the question. What is the multiplier for? What role does it serve?
float multiplier = 60f;
rb.AddForce(Vector2.up * jumpForce * multiplier * Time.deltaTime, ForceMode2D.Impulse);``` I use 60f, but what do you prefer?
I can't answer that question. I don't know what your multiplier is needed for.
Okay, here's the code I have so far: https://hatebin.com/yjeeqzfbzg
Also, you wouldn't use delta time with force either.
Sorry! I don't know what you mean by that.
Also, you would use force in a fixed update.
Go through the snipped of code that I quoted line by line,assuming that combo is equal to 2. What would it be equal at the end of the code snippet?
I would, but GetKey doesn't function well in FixedUpdate
Okay. But I don't see any scriptable objects in there.
Yep. You query input in update and apply forces in fixed update.
There is in the form of bossData, but I'm not sure if I'm doing it right.
I took it off and the player goes very high?
Ah, okay. I see it being used when setting the boss ho text. So what's the question?
Yes, because delta time is a very small number. You would need to compensate for it somewhere else in your formula.
At this point I'm not sure if you're using velocity or forces anymore.
I'm using rb.AddForce(). I am making the player jump
So what I'm looking to do is, when the current boss attached is defeated, it swaps to a different boss. So far I only have one instance of bossData for testing. Is there a way to do that or should I make multiple instances of bossData and attach them all?
Wdym..?
I didn't suggest any fixes yet.😅
Share the latest code.
Assuming you keep the logic as it is now, you can just assign a different BossData SO to use it's data.
void FixedUpdate() {
if (jumpInput) {
Jump();
}
}
void Jump() {
float multiplier = 60f;
rb.AddForce(Vector2.up * jumpForce * multiplier * Time.fixedDeltaTime, ForceMode2D.Impulse);
}```
Time.fixedDeltaTime does not belong there
You don't need to multiply by fixed delta.
in fact multiplier and Time.fixedDeltaTime are basically cancelling each other out
Or by any delta at all
and should both be removed
Okay, I was just wondering how to do it automatically when the previous boss is defeated. I'll admit, I'm still very new to scriptable objects.
When is Time.deltaTime supposed to be used then?
And you're yet to explain what purpose the multiplier serves.
when you need to convert a per-frame quantity to a per-second quantity
you don't just throw it around randomly
Must be an issue somewhere else. Debug your code.
To increase the speed so that jumpForce doesn't need to be a huge number. Instead jumpForce can be a small number and still have a huge impact
the only reason you have that problem is because you multiplied fixedDeltaTime in
This action is perframe
no it's not it's a jump
and forces don't ever need per frame adjustment
Assign the new so from whatever code is called when the boss is defeated.
If it were a left and right movement is it valid?
AddForce never needs deltaTime
it already has it built in
Okay, I'll look into that.
So it's basically a force multiplier. Which doesn't make any sense. "Make it be a small and nice number" is not a good enough reason.
If you want to go from a velocity expressed in units per second to figure out how far to move in a single frame, then you'd use deltaTime to get the distance for a single frame, for example. But when working with the physics engine it's doing that part for you. You don't need to worry about it
and randomly multiplying it in is causing you issues
See where you're resetting it and debug why it happens when you don't expect it to happen.
I'll study more about the subject. Thanks for the help!
unity says input axis leftStickVertical "isnt set up", yet I have, unless im missin somethin
this is for the right stick of a controller btw
ik theres a new input system but itll be harder to use since ive never used it before and this for a school assignment thats due in an hour and a half lol
why have you screenshotted rightStickVertical while the error speaks about leftStickVertical
because i forgor to save a script, error is gone but doesn work for some other reason
( and idk what it is this time )
4th axis is vertical and 5th axis is for horizontal on playstation controllers right?
and do i need to specify a JoyNum for this
I have no idea because I haven't used the old crappy input system in forever and the idea that the 4th axis has any meaning at all is stupid now there's a better system
id definitely use the new system if i wasnt time constrained this much lol
So, I'm making a scene manager. Its not a singleton and its attatched to a GameObject that exists in the scene it controls. This is the code I have so that it can be reference anything else without making the entire class static. I figured that since every GameObject in a scene is instantiated when you switch to that scene, I would need to reset it to the new, default scene manager. Am I correct?
public class InGameSceneManagerScript : MonoBehaviour
{
public static InGameSceneManagerScript Instance;
public void Awake()
{
Instance = this;
}
}
Its not a singleton
What your code is showing is the setup for a singleton
https://unity.huh.how/references/singletons
Well yeah, but I want everything in the scene to be able to easily reference it
I have the Instance = this so that when a new one is created when the scene is instantiated, it is assigned to the correct, new scene manager
Okay, but it's still a singleton. There is one of them at any point in time
The setup is fine, though not very robust
Yeah, it's definitely a simple singleton though (it doesn't account for multiple game managers for example). But yeah that reference will only point to one.
Ah, yes, sorry, I thought singletons were just things in DontDestroyOnLoad
Good to know for future reference
To be robust you would have to handle the case: If you were to load multiple scenes with this object in it then which one do you want? Destroying the one that isn't relevant
right here you will see theres 3 icons on the UI, they had used layout element to ignore vertical/horizontal layout groups
the apps need to deploy on windows, iphone, android and mac, so i need to make sure the icons will not go off when using different resoutions, the UI is "scale with screen size" with 1920X1080 tho, but ipad is 3:4 , more like 1800 X2400 , the UI will go off if the resolution is not 9:16
my question is , how to make sure the icons will auto adjust itself to the different resolution ratios, using code? or not
Is it really necessary? Its a simple game, and I wasn't planning on implementing anything like that
Then no, it's not
Sweet, thank you
Usually you check
if (Instance != null && Instance != this)
{
// make a decision
Destroy(this.gameObject);
}
Yeah, issue is its not in DontDestroyOnLoad, so every time the scene is instantiated, it will still be set to the old one and therefore not null
I wont worry about it though, it wont ever happen anyway
well, the previous scene is presumably unloaded, so it will evaluate to null
Yeah it's not uncommon to skip that for a game manager, but use it for a data system
anyone know how u can make smoothdamp much more less fps dependent?
cause when im on 30 fps the smoothdamp happens in 2 seconds
and when im at 600 fps it happens in 10 seconds
Oh, when a scene is unloaded, static variables are also deleted?
Ah, I see
(They are not actually null unless assigned to null, they just evaluate to null)
That makes a lot of sense
Unity making sense challenge (impossible) (world record)
Thanks!
Can someone help me about player health and damage? The code didn't have errors but it didn't damage on player
https://gdl.space/imerelabeg.cs
https://gdl.space/uvihemazix.cpp
put a debug inside where u compare tag
and check if it even detects the collision
make sure u spelled the tag correctly
Ah I see.
oh but also collision issue, you should debug it
if you want to safeguard this, on awake()
if(hp == 0) { hp = 100}
not recommended tho
When I debug it, it still run but didn't damage on Player
show the debug you put
I used
Debug.Log(collision);
Is that right?
show you are collide with the trap
depends where you put it
or you put it inside the if block?
also you should print the name + tag
I put it into OncollisionEnter2D
private void OnCollisionEnter2D(Collision2D collision)
{
Debug.Log($"collided with {collision.collider.name} with tag of {collision.gameObject.tag}");
if (collision.collider.CompareTag("Trap"))
{
PlayerHealth.TakeDamage(damage);
}
}```
didnt tell anything
private void OnCollisionEnter2D(Collision2D collision{
//1
if (collision.collider.CompareTag("Trap")){
//2
PlayerHealth.TakeDamage(damage);
}
}
```you have two places to put it into....
btw navarone already show you how to debug
so the tag is not Trap
you probably want to change it in the code to be "Player"
since a trap looking for "trap" tag makes not much sense
unless this is on the player?
Ah ok so what should I change in the code?
can you combine enum and getter at the same time?
is the trap script on a separate object than player?
trap script is separated.
public enum abc { if(.... ) {return abc.123;} }
You can have a property that returns any type you want.
soo yeah you want to look for "Player"
Enums aren't special
Ok I got it thanks.
although..you should look directly for PlayerHealth so you dont need to set a player reference for each trap
Alright.
if (collision.collider.TryGetComponent(out PlayerHealth playerHealth)
{
playerHealth.TakeDamage(damage);
}```
public enum Layout { land4_3, land16_9, land19_9, port9_16, port9_19, port3_4, NA }
public Layout Resolutions
{
get
{
if (1.4f > (Screen.width / Screen.height) > 1.3f)
{
return Layout.land4_3;
}
return Layout.NA;
}
}```
ty
its too bad all devices resolution always drift off by 0.1 or something
they might not be purely 16:9 or 19:9
they might be 15.7:9 or 18.6:9
Tysm
anyone please?
Share code.
public enum Layout { land4_3, land16_9, land19_9, port9_16, port9_19, port3_4, NA }
public Layout Resolutions
{
get
{
if (1.4f >= (Screen.width / Screen.height) || (Screen.width / Screen.height) >= 1.3f)
{
return Layout.land4_3;
}
if (1.8f >= (Screen.width / Screen.height) || (Screen.width / Screen.height) >= 1.7f)
{
return Layout.land16_9;
}
if ((Screen.width / Screen.height) > 2)
{
return Layout.land19_9;
}
if (0.8f >= (Screen.width / Screen.height) || (Screen.width / Screen.height) >= 0.7f)
{
return Layout.port3_4;
}
if (0.6f >= (Screen.width / Screen.height) || (Screen.width / Screen.height) >= 0.5f)
{
return Layout.port9_16;
}
if (0.5f > (Screen.width / Screen.height) || (Screen.width / Screen.height) >= 0.4f)
{
return Layout.port9_19;
}
return Layout.NA;
}
}
yall have a fix or know how to fix compile errors?
ive spent days trying to fix them
Read the error and fix them based on the information in the error and your !ide capabilities
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
trust me, when i say ive done everything, i MEAN everything
You were given specific instructions to provide the error details and code by several people...
There's no magic wand. You need to fix them one by one. Learn C# and you'll make fewer errors
Trust me, you haven't
I don't trust you.
having a fully configured IDE or VSC will activate intellisense to help you find out 90% possible errors
ok
old school way
capture a script that shows error, i need IDE view
lets see if ur IDE is really configured
ok
At some point you're going to actually have to show these errors rather than talking about them
A which one? 😂
I setup the AI Navigation using NavMeshAgents but when I try to use more than 3 agents the agents start to not work. For example in my scene I have the agents go towards an object in the scene while navigating through walls. When I add more than 3 agents some of them dont move for some reason? I checked the resources and it doesnt seem to be using that much so I don't know if theres a setting I have to change if I'm using multiple agents or what?
script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class PirateMovement : MonoBehaviour
{
public Transform target;
private NavMeshAgent navMeshAgent;
private void Start()
{
navMeshAgent = GetComponent<NavMeshAgent>();
if (navMeshAgent == null)
{
Debug.LogError("NavMeshAgent component not found on the pirate object!");
}
}
private void Update()
{
if (target != null && navMeshAgent != null)
{
navMeshAgent.SetDestination(target.position);
}
else
{
Debug.LogWarning("No target or NavMeshAgent component set for PirateMovement script!");
}
}
}
I’m such a noob
Just uninstall the Test Framework package from your project
The very first one
One would wonder why "one or more packages could not be added to the local file system"
package errors
did you try to purge the entire library files ? like delete the whole file
maybe you can try and see
Send the full contents of the first error.
JK IM NOT DUMB 🤣🤣
In vs?
No, in the Unity Console window.
the package is not valid
corrupted? or outdated?
welp maybe you should try to purge library files first?
Idk I’ve uninstalled unity and reinstalled it and I have EVERY editor
To me it seems like your Unity install is likely corrupt. However if you're not using Visual Scripting, Unity Version Control, or the Test Framework, you can try to remove them via the package manager and see if the project will open, but it's no guarantee things will continue working. Best bet is to reinstall Unity.
Hold on
When i overclocked my PCs ram I opened unity and it blue screened. Could that be the issue?
I did reinstall tho
You may have to clear the global package cache
https://unity.huh.how/package-manager/package-errors#reacquiring-corrupted-packages
I remember before I changed all the code that brought me down to one error which said c# 9.0 is not compatible with you thingy thing idk. The it said update your language version to 10.0 or later
are you sure you're adding the new ones with the same setting , like target is set n all ?
yea I duplicated the pirates so they are all exactly the same. I also tried removing the scripts and adding them back one by one but nothing changed
Idk what I did now it shows this
you have to look at the gizmos during playmode and see whey are they headed or not headed
!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.
Bro I’m so stressed I may actually cancel my game
https://hastebin.com/share/lenatubifi.csharp , https://hastebin.com/share/egumoxajaf.csharp , https://hastebin.com/share/yipehomiya.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
these are the code related to movment and unit selection
everything works fine, however i have an object i created called ground market, it simply is supposed to be a quad as a placeholder at the moment and does nothing but appears where you click once the unit starts moving there. if you have ever played an RTS game when you select a unit and right click to move that unit to a place there is a market or an arrow or somthing on the ground letting you know where you clicked and mine is not appearing
also if i can do anything or you have any tips to make my code more readable please let me know i always want to improve on readability
I get it man, shit gets hard! you can do it!
you can always hire someone on fiver to try and help you
if you are on a hard hump you cant figure out
minimize the problem because not appearing isn't enough information
debug position, debug if it's actually being initialized, debug that the material and shader is correct
Can someone know how to debug animation code?
animation code?
public Layout Resolutions
{
get
{
if (1.4f >= (Screen.width / Screen.height) || (Screen.width / Screen.height) >= 1.3f)
{
return Layout.land4_3;
}
if (1.8f >= (Screen.width / Screen.height) || (Screen.width / Screen.height) >= 1.7f)
{
return Layout.land16_9;
}
if ((Screen.width / Screen.height) > 2)
{
return Layout.land19_9;
}
if (0.8f >= (Screen.width / Screen.height) || (Screen.width / Screen.height) >= 0.7f)
{
return Layout.port3_4;
}
if (0.6f >= (Screen.width / Screen.height) || (Screen.width / Screen.height) >= 0.5f)
{
return Layout.port9_16;
}
if (0.5f > (Screen.width / Screen.height) || (Screen.width / Screen.height) >= 0.4f)
{
return Layout.port9_19;
}
return Layout.NA;
}
}```
output :
```cs
Debug.Log($">>> {Screen.width}"); // 1080
Debug.Log($">>> {Screen.height}"); //1920
Debug.Log($">>> {GameManager.Instance.Resolutions}"); //layout.land4_3```
why ?
1080/1920 is supposed to be < 1
ok i gotta make it into a function then .....
what am I looking at ?
That is the code Player controller, but the animation didn't work.
When I moved the character the animation isn't running instead the character just stand there and still move around
well you probably want this inside an else statement or something _animator.SetBool("isRunning", false);
You could also just have one at the bottom and dlete the one inside if statemtn and just do
_animator.SetBool("isRunning", horizontalInput != 0);
The animation worked after I used one at the bottom but how can I fix the animation when I turn left, the animation is not working.
did you debug what result you are getting, these are ints arent they?
also if (1.4f >= (Screen.width / Screen.height). If 1.4 is greater or equal to than a number you say is less than 1, whats the surprise that this code runs?
ty
THEY ARE SUPPOSED TO BE &&
i hate my braindead moment
and also 1080 / 1920 = 0 if we are talkin about ints
I don't have eyes there idk what "not working" means, you have to start debugging. Show animator setups
Alright.
I have a character who shoots bullets to the mouse pointer but the bullet slows down when the pointer is near the character and I don't know why
I normalize the vector generated between the character and the pointer
and then multiply the velocity of the bullet by that vector
show the code
but the calculation inside the getter is float right?
public class DisparoBala : MonoBehaviour
{
public GameObject balaPrefab;
public float velocidadBala = 10.0f;
public float tiempoDestruccionBala = 2.0f;
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
// Obtener la posición del mouse en la pantalla
Vector3 posicionMouse = Input.mousePosition;
Vector3 posicionMouseMundo = Camera.main.ScreenToWorldPoint(posicionMouse);
// Calcular la dirección del vector desde el personaje hasta el mouse
Vector3 direccion = (posicionMouseMundo - transform.position).normalized;
GameObject bala = Instantiate(balaPrefab, transform.position, Quaternion.identity);
bala.GetComponent<Rigidbody2D>().velocity = direccion * velocidadBala;
Destroy(bala, tiempoDestruccionBala);
}
}```
like 1.4f >= (width/height) , the result still a float
Here.
no it isnt, take it step by step. (Screen.width / Screen.height) = (int/int). this will give you 0
1.4f >= X is a boolean expression. the result is a bool
ohh right.. so left is going in the -
doh
thats myb
bool running = horizontalInput != 0;
animator.SetBool("isRunning", running);
Alright.
you know what make a bool for it
so its not crammed in a animator parameter
hm that does look fine although i have trouble fully reading it because of the mixed languages. I would just debug.log to make sure the velocity and its magnitude matches what you think it should be. In this case magnitude should be 10 always
Maybe some external code is affecting it
Alright ty.
oh, when i get the mouse pointer close to the character, the vector gets higher on Z
however im using 2D lol
so the bullet is not going slower, its just going through the Z axis apparently
ah yea 2d issues, i always forget that case because i do 3d 😅
just copy the Vector2 not V3
the bullet vector is made by the character vector and the pointer vector
the character vector is 3D
even tho im in a 2D environment
this should be
Vector2 posicionMouseMundo = Camera.main.ScreenToWorldPoint(Input.mousePosition);```
I substract the character's position to that vector
...is it considered poor form to cry in the chat room..?
asking for a friend
wat
I can see that
but character's position is 3D
wdym 3D?
why are you using rigidbody 2D
Vector2 direccion = (posicionMouseMundo - transform.position).normalized; i can't do this
because transform.position is 3D
its vector3
thats not the one I said to change to V2 lol
using oneOfDemNoo-Fangled-Mooses;
what
Stop trolling please
no one said that
I'm inferring too much
is your camera orthographic or prosp ?
ortho
you can also set the vectors z to 0 before normalizing it, since you probably dont care about the z axis
then it should work without the z for posicionMouseMundo
I think your Z was messing with it
like i wrote it would've omitted the z and set to 0 lol
nvm you solved it thats all it matters
Vector2 posicionMouseMundo = Camera.main.ScreenToWorldPoint(Input.mousePosition);
if its vector2, i can't substract transform.position to it
you would need to cast it
Vector3 direccion = ((Vector3)posicionMouseMundo - transform.position).normalized;
like you did it is perfectly fine though :p
thank you!
do I need everything to be a prefab?
I made an enemy prefab but I can't make it follow the player because I can't assing the player object to the enemy prefab's script
but if I make the player a prefab, the enemy detects the position of the prefab which is static
If you're instantiating objects at runtime, you'll need to pass/find the references via code.
Hello everyone
I have a scriptable object with fields made visible on the inspector.
One of these fields takes a GameObject which comes with a script of its own.
How can I make that GameObject script read the values of the variables set on the SO's inspector fields?
You can't. The reference must be the other way around.
if it really needs to, have the SO assign itself to the script on the gameobject. This does sound like an odd thing to need to do though
anyone have ideas on how to code excavator like controls for the rear of a wrecker style tow truck?
Quaternion.identity is the current rotation or the default rotation?
default. A rotation of zero
Ok, thxs
How would I go about moving something a certain way, in relation to other parts
For example, I have a tow truck, wrecker style, and I need to make certain parts lift up and down, certain parts slide in and out, and certain parts rotate in and out, BUT they need to do so in relation to the vehicle, not an axis. For example, the part that slides in and out, needs to slide in and out the exact same way wether its at a 90 degree angle, a 45 degree angle, parked in its resting position, or at any other angle
I need this highlighted part to slide straight in and out of the tube its attached to to the right, no matter what position that tube to the right is in. See next photo
Move it how you want and make it child of the object you want to move it in relation to
It is a child already, but I can't seem to get it to move right
make it child of the right tue
Probably need some parenting and inverse kinematics.
well based on axis shown, if those are local axis, you got problem right there
That way when I move parts they all stay connected
you need to move it 0.5 green and 0.5 blue axis
Yeah I had local axis selected by accident
Now its on global, but I still need to make it move the right way no matter its position. Whether its tilted up, or down, I need it to slide out of that shaft. Currently I'm not using animations, and I'm coding the transform, because I dont think there is a way to have an aniamtion work in the fashion I need it to. Button pushed, animation working, button not pushed, animation stays where it is, other button pushed, animation reverses from current position and retracts
i really have no idea where the problem is. if that arm is child of the tube, it will follow tube everywhere
share your movement !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.
-1 for reverse animation
but if you want programmers way, you can use DOTween
Im not asking for how to make it follow the tube, it does that fine, i need it to slide in and out of the tube the same way, no matter what angle the tube is at, and my code for that does not seem to 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.
post your code, because youre probably modifying your global pos and not local pos
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
// Slider Out
if (Input.GetKey(KeyCode.P))
{
float SliderYTransformValue = sliderArm.transform.position.y;
SliderYTransformValue--;
Vector3 sliderNewPosition = new Vector3(sliderArm.transform.position.x, SliderYTransformValue, sliderArm.transform.position.z);
sliderArm.transform.Translate(sliderNewPosition);
}
// Slider In
if (Input.GetKey(KeyCode.O))
{
float SliderZRotationValue = sliderArm.transform.rotation.z;
SliderZRotationValue++;
Vector3 sliderNewPosition = new Vector3(sliderArm.transform.rotation.x, sliderArm.transform.rotation.y, SliderZRotationValue);
sliderArm.transform.Translate(sliderNewPosition);
}
its small enough I figure here should be fine
and yes I know I am declaring the variable mutltiple times when I could set it to be a private var and just keep using it, thats for my code cleanup portion where I take care of nuances, right now im just playing with the system
so you should be using something like
transform.position += transform.forward * distanceToMove;
What is distance to move in this case? As its designed only to move when the button is held down
The idea is to have it replicate the operation of real hydraulics
the distance you want the slider to move
So, 1 unit per frame I guess?
what ever. the important thing is you must use one of the transform directions to get the correct direction of the move
I see
And now for a harder question. How can I make the movement stop at a certain point, like max extension
or, when it hits the terrain
for now I am okay with just max extension
clamp the distance moved
But the arm will probably ned physics at some point
I assume to do that I will need to note its position at what I want to be max, and then clamp it at the number choosen?
not it's position. The distance between the minimum position and the maximum position
Your going to have to help me a little more with that, I can do code okay, but trying to translate code to a 3d world is a bit hard for me still
// Slider Out
if (Input.GetKey(KeyCode.P))
{
sliderArm.transform.position += transform.forward * 1;
/* float SliderYTransformValue = sliderArm.transform.position.y;
SliderYTransformValue--;
Vector3 sliderNewPosition = new Vector3(sliderArm.transform.position.x, SliderYTransformValue, sliderArm.transform.position.z);
sliderArm.transform.Translate(sliderNewPosition);*/
}
This the only line i need then?
public void DoDamage(UnitStateMachine actor, float trueDamage, List<UnitStateMachine> targetList, int strikeCount, bool canCrit, bool isDodgeable, bool ignoresDef, AffectedStat affectedStat, bool isHeal, List<StatusEffectList> statusEffectLists)
{
//damage happens
}
is this kinda okay to use so much parameters for a method?
Not a great practice. Hard to read.
it may not be forward, that will depend on how your model is set up. but, basically, yes
Okay, and then I would love a bit more explaination on the clamping part
if you have an example that would be great
Consider creating a class or struct that encapsulates the params and pass an instance of it instead
transform.backwards? isnt a thing?
No, because you can do -forward
-transform.forward. May I suggest you follow some tutorials on Vectors before continuing
I will do that for sure. Code I understand, 3d worlds I understand, interlacing the two, not so much
well, you are gonna need it, a lot
the whole logic on the other side is performed by quite a massive SO which calculates the whole outcomes and well, then transfers them to this method.
Class or struct you mean like create a class that will hold all this information and then pass it?
Like (Pseudocode)
public class AttackInformation()
{
var blah;
var meh;
var ah;
}
AttackInformation AttackInfo = new ();
AttackInfo.blah = actor;
AttackInfo.meh = trueDamnage;
//
public void DoDamage (AttackInformation info)
{
//damage happens
}
?
Yes.
struct rather than class, but basically, yes
okay, that makes ssense, thank you
I am too noob to know about structs yet 🙂
then don't worry about it
I ahve to google what the struct is 🙂
@languid spire so here is the issue I have with the transform that you suggested, same issue I had with mine, when the arm is tilted up, it wont follow the proper path
now instead of following the direction that the retaining shaft is pointing, it continues to obey forward and backward
as I said, .forward may not be the one you need, it will depend on the model design. you need to try using other transform directions
its not about direction though, thats what I am saying. The shaft on the left tilts up and down independant of the part on the right sliding in and out of it
it is exactly about direction. The direction your model thinks is forward
but forward is a set direction decided by the 3d world, not relative to anything, am I not correct on that?
To make sure we are on the same page of how the motion needs to work independantly
that is Vector3.forward. transform.forward is relative to the transform not the world
why is it when I create a GameManager singleton (not singleton literally, it's just like this:)
public class GameManager : MonoBehaviour
{
public static GameManager instance;
void Awake()
{
if (instance == null)
{
instance = this;
}
else if (instance != this)
{
Destroy(gameObject);
}
DontDestroyOnLoad(gameObject);
}
}
it goes without any problems, when I do the same for different class, it gets error something about implementing custom monobehaviour behaviour?
that code is wrong anyway
Damn tell it like it is LOL
why? It's not, it's working and I've been using the whole class liek for last maybe 4 months (I have quite a big project)