#💻┃code-beginner

1 messages · Page 246 of 1

languid spire
#

That is, basically, what Unity is doing. The difference is you would be doing it in IL and Unity does it in native code, so Unity's implementation will be faster

verbal dome
#

Idk, check that you have the correct version for your tutorial (?)

silent vault
fleet breach
#

And he did have a forum explaning about it and i did the exact thing

#

still wont work

languid spire
whole isle
#

can somone expalin why my code is red

verbal dome
#

Do you have that package?

#

@fleet breach

whole isle
verbal dome
whole isle
#

wowuld it be better if i create 2 diffrent scrip instead

fleet breach
whole isle
#

nvmm

ruby python
silent vault
verbal dome
languid spire
#

yes, it will fire

ruby python
#

or rather OnTriggerStay() for your use case (I think)

silent vault
languid spire
#

OnCollisionEnter or OnTriggerEnter will fire on Instantiate

silent vault
fleet breach
silent vault
verbal dome
ruby python
#

ConfigurableJoint = my brain hurty lol.

fleet breach
#

anyways thanks a lot man

verbal dome
#

Might be something I cant remember rn but that should do it 🤔

ruby python
#

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.

languid spire
#

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

ruby python
#

Yeah I'm working in my 'test scene' atm trying to get this to work. lol.

vast vessel
#

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;
}
verbal dome
#

Search for weighted list implementations online

#

It's not super complex

ruby python
quaint flicker
#

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?

ruby python
#

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.

hidden lotus
#

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

ruby python
#

Check the syntax on AndroidJavaRunnable (never seen that before myself, so dunno what the syntax supposed to be)

languid spire
#

because line 9 makes no sense

hidden lotus
# languid spire 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

languid spire
hidden lotus
#

maybe i just accidently clicekd tabbed or something, im not sure

languid spire
#

you are the programmer, you bloody well should be sure of what you are doing

hidden lotus
#

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

dusky hazel
# hidden lotus yeah i did look at that and thought that it was a bit odd, however i was followi...

a great unity totorial once you are finished that one is https://learn.unity.com/course/create-with-code?uv=2022.3

Unity Learn

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...

lost anvil
#

for inventory systems, is it best to use ScriptableObjects or Interfaces?

hidden lotus
#

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

orchid trout
#

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

rare basin
#

did you put Debug.Log("onValidate", gameObject)

#

to check what object is calling it?

orchid trout
#

I tried to debug its 'name' but that didnt help me find it

#

Ill try what you suggest now

rare basin
#

you will get a message in the console

#

after you click on it

#

it will show you what object called the debug.log

languid spire
orchid trout
orchid trout
zenith cypress
rare basin
#

in the hierarchy

orchid trout
#

I click on the error and nothing in highearchy highlights, nothing selects, nothing occurs

languid spire
rare basin
#

i didint ask you to click on the error

orchid trout
#

"you will get a message in the console
after you click on it"

rare basin
#

yup

orchid trout
#

Define "it"

rare basin
orchid trout
#

"i didint ask you to click on the error"
is the console field not 'the error'

#

What is the is

rare basin
#

lol

orchid trout
#

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

zenith cypress
#

The onValidate one

orchid trout
#

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

rare basin
#

do you know what a error is

#

clearly not

#

Debug.Log is not a error

orchid trout
#

Like I said, already, I clicked that, and nothing occured

orchid trout
rare basin
#

what lmao

fickle plume
#

It highlights as soon as it is selected. Switch away from it to another line then click again to see highlight

orchid trout
#

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

rare basin
#

show the Debug.Log

#

in code

#

100% you didint do it exactly as i told you to do it

orchid trout
#

There is no selection occuring, no highlighting

rare basin
#

because you just did Debug.Log("onValidate");

orchid trout
#

I did exactly what you told me to do

#

I copied your code directly

zenith cypress
#

Super weird, just tested on my end and it works in that function (assumed maybe it was blocking somehow)

orchid trout
#

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

rare basin
fickle plume
#

Error could have halted highlighting behavior

rare basin
#

leave just the debug.log

zenith cypress
#

Can also put the object in the LogError as well (also supports that). Although it should be working already in the normal log itself 🤔

orchid trout
#

Just the debug, shows up twice in console, clicking the console messages (either) highlights nothing in hierarchy

zenith cypress
#

the heck

rare basin
#

and show the result

#

then search the hierarchy by that printed name

orchid trout
#

I am glad that you think this is crazy because it validates my feeling that this shouldn't be possible

#

and makes no sense

rare basin
#

also open Project tab, next to your console

orchid trout
rare basin
#

perhaps your project file is being higlighted

#

not a object in the scene

fickle plume
#

You just likely debugging the null object.

#

Should make sure it exists first

swift crag
#

yes, if this game object is coming from an asset, the context will take you to the project window

orchid trout
#

None exist in scene

rare basin
#

and see if any file from Project tab

#

is being higlihted

zenith cypress
#

Yeah check the project panel

rare basin
#

move it to the side so you see both windows at the same time

zenith cypress
#

OnValidate will fire for prefabs on script reload

orchid trout
#

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.

rare basin
#

yup

#

so there is your answer

zenith cypress
rare basin
#

OnValidate isn't only called on instances, but also on prefabs

orchid trout
#

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?

rare basin
#

no

swift crag
#

It's more general than that.

rare basin
#

did you read the OnValidate docs

swift crag
#

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

zenith cypress
#

Yeah so the first part is this case for example

swift crag
#

actually, what is "script" here? I presume it means "when the instance is created"

orchid trout
#

Are you asking me? The script here is ```public class InitiativeEntry : MonoBehaviour

swift crag
#

No, I'm looking at the doc line I quoted

orchid trout
#

Oh 'the script' from the doc

swift crag
#

the scary part is that OnValidate can run on threads other than the main thread

zenith cypress
#

@swift crag near the end

swift crag
#

which results in mysterious behavior if you try to interact with the rest of Unity's API

zenith cypress
#

ye, cool chart

swift crag
icy junco
#

what is the best way to learn unity?

languid spire
eternal falconBOT
#

:teacher: Unity Learn ↗

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

orchid trout
#

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

night mural
orchid trout
#

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?

swift crag
#

I would not be surprised if the second prefab was still loaded by the editor

night mural
#

yep i think onvalidate gets called by the editor and doesn't care if the thing is in the scene or not

swift crag
#

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

orchid trout
#

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 UnityChanThink

zenith cypress
#

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

swift crag
#

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)

pallid nymph
pallid nymph
#

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 😒

swift crag
#

so far, I've only really used OnValidate to copy an asset's GUID into a field on a component

proven herald
#

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?

swift crag
#

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

orchid trout
#

but yeah only good for debugging, not meant for actual build

proven herald
swift crag
proven herald
swift crag
#

sharedMaterial doesn't make a unique copy

proven herald
#

@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;
     }
 }```
swift crag
#

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

proven herald
#

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

swift crag
#

Serialize _infoLightMaterial so that we can look at it in the inspector

#

(and do the same for the mainenance light material)

proven herald
#

okay

swift crag
#

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

proven herald
#

omg i get it now

swift crag
#

oh right, there's also debug mode

#

and hmm, that looks like the wrong material (:

proven herald
#

thanks a lot, basically when i place the building there's a material that's changed

swift crag
#

was something else setting it?

#

yeah

#

that'll do it

proven herald
#

yeah.. was wrong about no other script affecting it

#

ty!

ruby python
#

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.

https://pastebin.com/8EKjEpg7

Could anyone please point out where I'm being an idiot please?

https://streamable.com/fgt2xn

Watch "2024-03-10 17-56-28" on Streamable.

▶ Play video
swift crag
#

this is the Z component of the quaternion vector

#

You probably wanted eagleRoot.eulerAngles.z

ruby python
#

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.

swift crag
#

share the updated script

ruby python
#

!code

eternal falconBOT
ruby python
#
 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);
    }
swift crag
# ruby python

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

ruby python
#

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)

swift crag
#

It's rotating around its X axis.

#

The blue arrow moves as a result, yes

#

but the rotation is purely around the X axis

ruby python
#

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

swift crag
#

Neither image shows anything being rotated around its Z axis, so I don't understand what you're talking about

ruby python
#

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.

swift crag
#

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

cunning silo
#

um can someone help me with unity ?

ruby python
#

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. 😕

swift crag
#

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

cunning silo
#

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 🙏

swift crag
#

ask your question

#

i don'tk now what "the unity preference" means

cunning silo
#

let me show me then

swift crag
ruby python
#

Driving me nuts. lol.

swift crag
#

first, to sanity-check this, what happens if you just copy the rotation of the ship?

cunning silo
swift crag
#

you don't edit your script inside unity

#

you use a code editor

#

you should follow a course on !learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

swift crag
#

it will teach you how to use the editor

swift crag
#

i'm going to see if i can recreate your problem

ruby python
cunning silo
swift crag
#

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

ruby python
#

Ship Orientation

#

Rotates Left/Right around it's Z Axis and it always pointed to the center of the moon.

final trellis
#
rb.AddForce(Vector2.down * recoilForce);

how do I make this line of code have Vector2.down be relative to a referenced Transform

swift crag
#

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

swift crag
#

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.

ruby python
#

I've tried 'localEulerAngles.z' and it didn't change anything. 😕

swift crag
#

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.

ruby python
#

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. 😕

swift crag
#

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

swift crag
#

so that's just world rotation anyway

summer stump
#

If you ask, then maybe

Woah, massive lag... sorry

swift crag
#

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

ruby python
#

Okay, I'll have a read and see if I can get it work. Rotations alway, without fail trip me up.

swift crag
#

Sticking to quaternion methods and multiplication makes a lot of those problems go away

swift crag
ruby python
swift crag
swift crag
ruby python
#

Just swtiching an Axis.

swift crag
#

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

swift crag
ruby python
#

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.

ruby python
#

It's working as expected now, thank you. Really appreciate your help (And Patience. lol.)

swift crag
#

it breaks once you’re no longer aligned with an axis

#

and good!

#

You can adjust the angle to change the amount of tilt

ruby python
#

Yeah, already got that bit variabled up. lol.

summer locust
#

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?

ruby python
#

Use ForceMode.Acceration I think it is.

#

Maybe Impulse? (not massively conversant on the different types tbh.

craggy laurel
#

Can I use Animator/Animation for UI as well? Or is it designed for regular GameObjects and there's a different system for UI

swift crag
#

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

craggy laurel
# ruby python Yes you can.

When I use the Sprites in UI Animations they are extremely small (obviously). What's the best approach to make them bigger?

ruby python
swift crag
#

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

summer locust
#

yes thats what i did and it works great for jumping but not side to side movemeny

swift crag
#
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

summer locust
#

ok

#

ill give it a shot

swift crag
#

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

summer locust
#

wait for clamping how do i set in a specific number ?

swift crag
#

just fixed it

swift crag
summer locust
#

thank you and would it work the same for 2d

swift crag
#

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

summer locust
#

IT WORKS

swift crag
#

argh, I am bad at typing code on my ipad :p

#

there we go

summer locust
#

wait

#

I added the cap which works great for side to side but now my jump is capped and it barley jumps

swift crag
#

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.

summer locust
#

thank you it worked

tulip stag
#

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

short hazel
tulip stag
#

goat

ocean dove
whole isle
#

with this code that ive used

#

there always 1 heart left showing

#

even thought the player dead

swift crag
#

is 0 < 0 true or false?

ocean dove
#

pretty sure if checks are slower than just doing Mathf.Clamp(health, 0, maxHealth); for your health clamp

ocean dove
#

since 0 cannot be greater than 0

pseudo cypress
ocean dove
#

but that depends on is it an int or a float

pseudo cypress
#

Sorry for bad quality

swift crag
#

right, i was posing the question to Mirage :p

ocean dove
#

with a float it might be true or even false

swift crag
#

if two floats are both exactly 0, it'll always be false

ocean dove
#

Floating point errors exist but I'm unsure since I never tried checking is float 0 greater than float 0

whole isle
swift crag
wintry quarry
swift crag
# whole isle

ah, you destroy the game object when your health hits 0

ocean dove
#

floating point errors could mean that 0 is actually 0.0000001 or anything close to that really

swift crag
#

no, they don't

#

0 is 0

swift crag
whole isle
wintry quarry
#

now if you did a calculation that should end up with 0 it might end up being slightly not zero

ocean dove
#

Okay well, too lazy to explain floats to you by now so I'll be going now

wintry quarry
#

but if you type (0f < 0f) it will be false

swift crag
#

Call that function after you take damage and in Update

swift crag
swift crag
ocean dove
#

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

whole isle
#

i removed the equal siggn no it the charchter still alive when 0 hearts are showing

swift crag
#

health <= 0 is the correct condition for being dead.

swift crag
#

Destroying the game object means that Update doesn't get to run anymore

#

(because the object and all of its components are gone)

whole isle
#

i thought it was already seprated

swift crag
#
void Update() {
  DoHealthbar();
  // other stuff that happens every frame
}

void Damage() {
  // reduce your health here
  DoHealthbar();
}

void DoHealthbar() {
  // code that updates the health display
}
whole isle
#

isnt mine like that ?

swift crag
#

No. You have all of your healthbar code in Update.

#

Move it out of Update and into another method.

whole isle
#

cant i just replace the word update

swift crag
#

no, because then you won't have an Update method being called every frame

#

do you not understand what Update does?

whole isle
#

oh ok that make sene

swift crag
#

that will work. It's only really important in TakeDamage, since IncreaseHealth won't destroy your game object

whole isle
swift crag
#

yes, that will be fine

whole isle
#

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?

swift crag
#

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.

whole isle
#

oh ok thx before it didnt update cause it didnt update as the objext was destroyed?

swift crag
#

Right.

#

Your PlayerHealth component was destroyed when you destroyed gameObject (since destroying a game object also destroys all of its components)

whole isle
#

ok thanks alot that was helpful

final trellis
#

how do i convert a number between 0 and 1.6 to 0 to 1, this is for the purposes of a lerp function

steel smelt
#

@final trellis x / 1.6

final trellis
#

thanks! google results were significantly more complex than that lol

short hazel
swift crag
#

I use InverseLerp even for simpler cases

#

it clearly indicates what you're doing

tender stag
#

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?

grizzled surge
#

Do someone want to help me create a 3,2,1 GO countdown for my game?

swift crag
#

using deltaTime is wrong

#

it will fix the issue; you probably just didn't recompile or something

tender stag
#

does this goes for smooth damp as well?

swift crag
dire tartan
#

im not sure whether this is a coding issue but objects look very blurry when i move and turn

swift crag
#

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

tender stag
#

its still slower when in full screen

swift crag
#

You probably have incorrect logic somewhere else

tender stag
#

this is the logic

swift crag
#

how do you calculate position ?

tender stag
#

Vector3 position = new Vector3(ladder.bottomStartPosition.position.x, ladder.bottomStartPosition.position.y, ladder.bottomStartPosition.position.z);

#

wait i dont need that anyways

swift crag
#

and then how do you change the target position?

tender stag
swift crag
#

ah, you're using it to attach to the ladder, not to move up the ladder

tender stag
#

yeah

#

but moving up the ladder is also broken

#

works slower and faster

#

depending if ur fullscreened

swift crag
#

share the entire script?

tender stag
#

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

rare basin
#

that's not good

tender stag
#

not really

rare basin
#

ever heard of single-responsibility rule?

tender stag
#

just movement script

rare basin
#

with probably 30 if/else statements?

tender stag
tender stag
swift crag
tender stag
#

been making this for 2 months

swift crag
#

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

tender stag
#

but without it it'll do the same thing

#

like with the ladders

swift crag
#

there may be slight differences depending on framerate, especially as you get really close to the target

tender stag
#

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;

swift crag
#

no, that isn't relevant

tender stag
#

might be

#

im on unity 2020

swift crag
#

no, it is not relevant. there is literally no difference.

#

it doesn't matter what your unity version is

vast ivy
#

does the component Nav Mesh Agent no longer exist?

summer stump
vast ivy
summer stump
vast ivy
#

I do not, let me do that

#

ok I got it, thanks!

tender stag
#

i think it might be that

tacit birch
#

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

thorn holly
#

Can you post your code?

wintry quarry
tacit birch
#

Ah give me a second then. I have to pull the 4-directional one from my old project

crisp mountain
#

so generally how much should i study the unity docs for programming?

thorn holly
#

What do you mean study docs? Like are you just looking at random stuff in the docs?

crisp mountain
#

looking at docs for trying to find solutions to problems, not really knowing what to do

thorn holly
#

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

crisp mountain
#

not really, most of my coding knowledge is python, but i know the basics id say

thorn holly
#

Well, starting off, learn some c#

wintry quarry
wintry quarry
crisp mountain
#

i mean, i know the basics of c#, but i know a bit more about python

rustic bison
#

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?

thorn holly
crisp mountain
#

mostly c# related

thorn holly
thorn holly
crisp mountain
#

its not about an issue im currently on, im just looking for ways to improve at scripting

wintry quarry
#

Learn C# outside of Unity first

thorn holly
#

Does that make sense? I could use your specific case as an example if it doesn’t.

wintry quarry
crisp mountain
#

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

thorn holly
rustic bison
crisp mountain
#

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

pallid nymph
rustic bison
#

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

thorn holly
rustic bison
#

Looks like there's different stages that are scenes? Is that where you're going with this?

abstract onyx
#
    {
        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
wintry quarry
thorn holly
# rustic bison I think I know what youre talking about, never played it though

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.

wintry quarry
#

Which means the audio source is going to be destroyed. @abstract onyx

abstract onyx
#

How can I do this then? Any ideas?

#

Thanks for the help btw!

wintry quarry
#

do what

abstract onyx
#

play the sound on death before the new scene gets loaded

wintry quarry
#

Don't load the new scene until the sound is done playing

north kiln
#

Also use CompareTag instead of equality

rustic bison
abstract onyx
#

oh I see, let me try, thanks again!

thorn holly
tender stag
#

how can i fix smoothdamp running faster at lower fps?

rustic bison
#

Alright thanks, I think I have a better idea of it now

cunning silo
tacit birch
summer stump
eternal falconBOT
tacit birch
#

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

lost marsh
#

I like coding but idk what to code that will be fun

teal viper
#

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.

tacit birch
#

Ah I've tried A* Pathfinding but I couldn't figure out how to set it to 4-directions only

teal viper
#

Read the documentation

barren violet
rancid tinsel
#

is this outdated? didnt have this error last night

north kiln
#

Why are you using GraphView

rancid tinsel
#

actually idk how it got there thinking about it now

north kiln
#

Then remove it?

#

Also, if your IDE isn't underlining errors in red you need to configure it !ide

eternal falconBOT
rancid tinsel
#

it is configured but that error isn't getting underlined

#

it only shows it when building the project

north kiln
#

You can't use UnityEditor code in a build, so that's why that occurs

rancid tinsel
#

now im getting this

#

only when building

north kiln
#

Same problem.

rancid tinsel
#

oh right

#

makes sense

vapid lintel
#

Hey, so if I attach multiple enemy scriptable objects to a script, what's the best way to swap between these objects?

teal viper
#

What happens here if combo is currently == 2?

        if (combo < 3)
        {
            combo++;
        }
vapid lintel
small mantle
#

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); }

teal viper
#

You didn't answer my question.

#

Share the error details.

teal viper
teal viper
small mantle
teal viper
#

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.

vapid lintel
teal viper
small mantle
teal viper
#

No.

#

Velocity is used by the physics system and is multiplied by the fixed delta time before moving the object.

vapid lintel
#

!code

eternal falconBOT
small mantle
teal viper
small mantle
teal viper
#

I can't answer that question. I don't know what your multiplier is needed for.

teal viper
astral topaz
teal viper
teal viper
small mantle
teal viper
teal viper
vapid lintel
small mantle
teal viper
teal viper
#

At this point I'm not sure if you're using velocity or forces anymore.

small mantle
vapid lintel
teal viper
#

Wdym..?
I didn't suggest any fixes yet.😅

teal viper
teal viper
small mantle
# teal viper Share the latest code.
void FixedUpdate() {
        if (jumpInput) {
            Jump();
        }
    }

    void Jump() {
        float multiplier = 60f;

        rb.AddForce(Vector2.up * jumpForce * multiplier * Time.fixedDeltaTime, ForceMode2D.Impulse);
    }```
wintry quarry
#

Time.fixedDeltaTime does not belong there

teal viper
wintry quarry
#

in fact multiplier and Time.fixedDeltaTime are basically cancelling each other out

teal viper
#

Or by any delta at all

wintry quarry
#

and should both be removed

vapid lintel
small mantle
teal viper
wintry quarry
#

you don't just throw it around randomly

teal viper
#

Must be an issue somewhere else. Debug your code.

small mantle
wintry quarry
small mantle
wintry quarry
#

and forces don't ever need per frame adjustment

teal viper
small mantle
wintry quarry
#

it already has it built in

vapid lintel
teal viper
wintry quarry
# small mantle If it were a left and right movement is it valid?

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

teal viper
#

See where you're resetting it and debug why it happens when you don't expect it to happen.

small mantle
#

I'll study more about the subject. Thanks for the help!

final trellis
#

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

north kiln
#

why have you screenshotted rightStickVertical while the error speaks about leftStickVertical

final trellis
#

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

north kiln
final trellis
#

id definitely use the new system if i wasnt time constrained this much lol

thorn holly
#

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;
    }
}
north kiln
thorn holly
#

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

north kiln
#

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

tough lagoon
thorn holly
#

Ah, yes, sorry, I thought singletons were just things in DontDestroyOnLoad

#

Good to know for future reference

north kiln
#

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

nimble apex
#

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

thorn holly
north kiln
#

Then no, it's not

thorn holly
#

Sweet, thank you

tough lagoon
#

Usually you check

if (Instance != null && Instance != this) 
{
  // make a decision
  Destroy(this.gameObject);
}
thorn holly
#

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

north kiln
#

well, the previous scene is presumably unloaded, so it will evaluate to null

tough lagoon
#

Yeah it's not uncommon to skip that for a game manager, but use it for a data system

tender stag
#

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

thorn holly
north kiln
#

No

#

Unity Objects evaluate to null when they are destroyed

thorn holly
#

Ah, I see

north kiln
#

(They are not actually null unless assigned to null, they just evaluate to null)

thorn holly
#

That makes a lot of sense

#

Unity making sense challenge (impossible) (world record)

#

Thanks!

raw sun
tender stag
#

put a debug inside where u compare tag

#

and check if it even detects the collision

#

make sure u spelled the tag correctly

raw sun
#

When I ran, the health is 0 and it didn't set like max health I have been set up.

rich adder
raw sun
#

Ah I see.

rich adder
#

oh but also collision issue, you should debug it

nimble apex
#

not recommended tho

raw sun
#

When I debug it, it still run but didn't damage on Player

rich adder
raw sun
#

I used

Debug.Log(collision);

Is that right?

gaunt ice
#

show you are collide with the trap

rich adder
gaunt ice
#

or you put it inside the if block?

rich adder
#

also you should print the name + tag

raw sun
#

I put it into OncollisionEnter2D

rich adder
#
 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);
        }
    }```
gaunt ice
#

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

raw sun
rich adder
#

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?

raw sun
#

Ah ok so what should I change in the code?

nimble apex
#

can you combine enum and getter at the same time?

rich adder
raw sun
#

trap script is separated.

nimble apex
#

public enum abc { if(.... ) {return abc.123;} }

wintry quarry
rich adder
wintry quarry
#

Enums aren't special

raw sun
rich adder
raw sun
#

Alright.

rich adder
# raw sun Alright.
 if (collision.collider.TryGetComponent(out PlayerHealth playerHealth)
        {
            playerHealth.TakeDamage(damage);
        }```
nimble apex
#

  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;
    }
  }```
teal viper
#

&&

#

Or ||

nimble apex
#

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

nimble apex
#
  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;
    }
  }
tiny zephyr
#

yall have a fix or know how to fix compile errors?

#

ive spent days trying to fix them

north kiln
#

Read the error and fix them based on the information in the error and your !ide capabilities

eternal falconBOT
tiny zephyr
#

trust me, when i say ive done everything, i MEAN everything

teal viper
wintry quarry
wintry quarry
north kiln
nimble apex
#

ok

#

old school way

nimble apex
#

lets see if ur IDE is really configured

tiny zephyr
#

ok

frosty hound
#

At some point you're going to actually have to show these errors rather than talking about them

tiny zephyr
#

A which one? 😂

vast ivy
#

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!");
        }
    }
}
tiny zephyr
#

I’m such a noob

wintry quarry
north kiln
#

One would wonder why "one or more packages could not be added to the local file system"

nimble apex
#

package errors

#

did you try to purge the entire library files ? like delete the whole file

#

maybe you can try and see

tiny zephyr
#

Do t think so

#

Which file is it

#

System 32?

nimble apex
#

wait???

#

no

north kiln
#

Send the full contents of the first error.

tiny zephyr
#

JK IM NOT DUMB 🤣🤣

tiny zephyr
north kiln
tiny zephyr
#

Oh

#

It’s this right?

nimble apex
#

the package is not valid

#

corrupted? or outdated?

#

welp maybe you should try to purge library files first?

tiny zephyr
#

Idk I’ve uninstalled unity and reinstalled it and I have EVERY editor

north kiln
# tiny zephyr It’s this right?

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.

tiny zephyr
#

Hold on

#

When i overclocked my PCs ram I opened unity and it blue screened. Could that be the issue?

north kiln
tiny zephyr
#

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

rich adder
vast ivy
tiny zephyr
#

Idk what I did now it shows this

rich adder
thick jetty
#

!code

eternal falconBOT
tiny zephyr
#

Bro I’m so stressed I may actually cancel my game

thick jetty
#
#

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

thick jetty
#

you can always hire someone on fiver to try and help you

#

if you are on a hard hump you cant figure out

timber tide
#

debug position, debug if it's actually being initialized, debug that the material and shader is correct

raw sun
#

Can someone know how to debug animation code?

rich adder
nimble apex
#
  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 .....

rich adder
raw sun
#

That is the code Player controller, but the animation didn't work.

rich adder
#

wdym "didn't work"

#

also you're setting isRunning immediately to false after true

raw sun
#

When I moved the character the animation isn't running instead the character just stand there and still move around

rich adder
#

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);

raw sun
eternal needle
# nimble apex 1080/1920 is supposed to be < 1

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?

nimble apex
#

its ORRRRRR

#

damn

nimble apex
#

THEY ARE SUPPOSED TO BE &&

#

i hate my braindead moment

eternal needle
#

and also 1080 / 1920 = 0 if we are talkin about ints

rich adder
raw sun
#

Alright.

turbid shuttle
#

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

eternal needle
#

show the code

nimble apex
turbid shuttle
#

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);
        }
    }```
nimble apex
#

like 1.4f >= (width/height) , the result still a float

eternal needle
rich adder
#

doh

#

thats myb

#

bool running = horizontalInput != 0;
animator.SetBool("isRunning", running);

raw sun
#

Alright.

rich adder
#

so its not crammed in a animator parameter

eternal needle
raw sun
turbid shuttle
#

however im using 2D lol

#

so the bullet is not going slower, its just going through the Z axis apparently

eternal needle
#

ah yea 2d issues, i always forget that case because i do 3d 😅

turbid shuttle
#

how do I make transform.position 2D

#

😅

rich adder
#

just copy the Vector2 not V3

turbid shuttle
#

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

rich adder
#

this should be

Vector2 posicionMouseMundo  = Camera.main.ScreenToWorldPoint(Input.mousePosition);```
turbid shuttle
#

I substract the character's position to that vector

minor patio
#

...is it considered poor form to cry in the chat room..?
asking for a friend

rich adder
#

I can see that

turbid shuttle
#

but character's position is 3D

rich adder
#

why are you using rigidbody 2D

turbid shuttle
#

Vector2 direccion = (posicionMouseMundo - transform.position).normalized; i can't do this

#

because transform.position is 3D

#

its vector3

rich adder
#

thats not the one I said to change to V2 lol

minor patio
turbid shuttle
#

what

summer stump
minor patio
#

transform.position needs to be 2d for mouse position?

#

oh, nevermind

rich adder
minor patio
#

I'm inferring too much

rich adder
turbid shuttle
#

ortho

eternal needle
rich adder
#

I think your Z was messing with it

turbid shuttle
#

yes

#

I just realized that

#

posicionMouseMundo.z = 0; did the trick

rich adder
#

like i wrote it would've omitted the z and set to 0 lol

turbid shuttle
#

sorry i dont understand

#

how did you wrote it

rich adder
#

nvm you solved it thats all it matters

rich adder
turbid shuttle
#

if its vector2, i can't substract transform.position to it

rich adder
#

you would need to cast it

#

Vector3 direccion = ((Vector3)posicionMouseMundo - transform.position).normalized;

#

like you did it is perfectly fine though :p

turbid shuttle
#

thank you!

turbid shuttle
#

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

teal viper
quasi steeple
#

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?

keen dew
#

You can't. The reference must be the other way around.

eternal needle
sterile moon
#

anyone have ideas on how to code excavator like controls for the rear of a wrecker style tow truck?

rich egret
#

hi

#

I accidentally deleted the prefab of the player, where can I download it again?

frigid sequoia
#

Quaternion.identity is the current rotation or the default rotation?

languid spire
frigid sequoia
sterile moon
#

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

sand glen
sterile moon
#

It is a child already, but I can't seem to get it to move right

sand glen
#

make it child of the right tue

static bay
sterile moon
#

All the parenting is set up

sand glen
sterile moon
#

That way when I move parts they all stay connected

sand glen
#

you need to move it 0.5 green and 0.5 blue axis

sterile moon
#

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

sand glen
#

i really have no idea where the problem is. if that arm is child of the tube, it will follow tube everywhere

languid spire
#

share your movement !code

eternal falconBOT
sand glen
#

-1 for reverse animation

#

but if you want programmers way, you can use DOTween

sterile moon
cobalt pike
#

The same problem as in the video occurs. Is there any way to solve it?

languid spire
#

!code

eternal falconBOT
sand glen
cobalt pike
sterile moon
#
            // 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

languid spire
#

so you should be using something like

transform.position += transform.forward * distanceToMove;
sterile moon
#

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

languid spire
#

the distance you want the slider to move

sterile moon
#

So, 1 unit per frame I guess?

languid spire
#

what ever. the important thing is you must use one of the transform directions to get the correct direction of the move

sterile moon
#

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

languid spire
#

clamp the distance moved

sterile moon
#

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?

languid spire
#

not it's position. The distance between the minimum position and the maximum position

sterile moon
#

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?

visual hedge
#
    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?

teal viper
languid spire
sterile moon
#

Okay, and then I would love a bit more explaination on the clamping part

#

if you have an example that would be great

teal viper
sterile moon
#

transform.backwards? isnt a thing?

teal viper
#

No, because you can do -forward

languid spire
sterile moon
#

I will do that for sure. Code I understand, 3d worlds I understand, interlacing the two, not so much

languid spire
#

well, you are gonna need it, a lot

visual hedge
# teal viper Not a great practice. Hard to read.

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
}

?

languid spire
#

struct rather than class, but basically, yes

visual hedge
visual hedge
languid spire
#

then don't worry about it

visual hedge
#

I ahve to google what the struct is 🙂

sterile moon
#

@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

languid spire
#

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

sterile moon
#

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

languid spire
#

it is exactly about direction. The direction your model thinks is forward

sterile moon
#

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

languid spire
#

that is Vector3.forward. transform.forward is relative to the transform not the world

sterile moon
#

Ahhh

#

Okay

visual hedge
#

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?

languid spire
#

that code is wrong anyway

sterile moon
#

Damn tell it like it is LOL

visual hedge