#💻┃code-beginner

1 messages · Page 733 of 1

earnest wind
#

yes

#

but i dont know when the player comes in

slender nymph
#

you fire the event when the player is spawned

earnest wind
#

he can come in later

rich adder
#

have it register itself

earnest wind
slender nymph
#

that's like, the whole point of using events. you use them to respond to certain things that can happen at any time.

rich adder
#

you can even make the event static , this is pretty handy if you have more than one player joining.. you can sub to 1 event and get different players
public static event Action<Player>OnPlayerSpawn;
//player
Spawn(){ OnPlayerSpawn?.Invoke(this)

you don't need to then sub to each instance

earnest wind
#

actually thanks a lot guys

#

i just changed a lot of the game logic now

#

it just hit my head that i can just make an Instance to the PlayerManager - the thing that spawns the player

#

and dont need to carry around the reference and pass it along with all of the other scripts when they need it

rich adder
#

its the great thing about this there are so many ways to solve a problem

earnest wind
rich adder
#

yeah when you don't know better but then you learn better, realize mistakes and learn / get exp

winged ridge
#

There's a saying "There's more than one way to skin a cat" implying that you can do the same task in many ways and get the same result, code is very much like that, as long as it works there's no real right or wrong way

polar dust
#

the motto I live by
if it works, it works

#

once it works, move on to the next thing

winged ridge
#

Very good motto. Always helps with bug fixing: is it game breaking if yes fix it now, is it annoying but won't break the game but worth circling back to, if yes do it later. Is it just visual and not a bug that affects gameplay. If yes does it have to be fixed?

grand snow
#

tech debt is a thing so if it "works" but its implemented poorly it will come back to haunt you

#

its relative to each project though so for quick things it may never matter

polar acorn
#
  1. Make it run
  2. Make it right
  3. Make it fast

In that order.

earnest wind
#

Happily fixed them all last week, so everything is as smooth as it can be (pretty sure someone can find a way to make it faster, but it runs at max fps for me so its okay)

polar dust
#

what takes practice is knowing when its appropriate to address certain issues early on before they become a real problem

stray lake
#

Hello

#

I'm new here, nice to meet you all

zenith mantle
#

same

#

what's wrong with this 🙏 im following a tutorial from 2023

rich adder
zenith mantle
rich adder
#

did you make hit a RaycastCommand ?

polar acorn
zenith mantle
polar acorn
#

Look for what type the out parameter is here

rich adder
#

and your IDE looks configured, it also shows in signature as you type

zenith mantle
polar acorn
zenith mantle
winged ridge
polar acorn
winged ridge
#

Love that website, great references and examples on it

rich adder
#

in the docs link sent, look at the signature has the out keyword you will be able to tell quickly which type you need

#

RaycastCommand aint the one

surreal ingot
#

Hi, i am trying to make a 2d flight controller for a new game I'm developing and was seeing if anyone could help me out. I'm still figuring stuff out any, help would be really appreciated!

winged ridge
dense goblet
#

quick question, any quick functions that wait one second before the next line of code\

winged ridge
dense goblet
#

tyty

slender nymph
# dense goblet tyty

note that coroutines do not delay the code where they are called from (unless the startcoroutine call is yielded within another coroutine), coroutines only delay the code within the coroutine

winged ridge
slender nymph
#

What I personally like to do is have a static coroutine method on a utility class that takes an action and a delay parameter, waits for the delay then invokes the action like this:

public static IEnumerator DelayAction(Action action, float delay)
{
  yield return new WaitForSeconds(delay);
  action?.Invoke();
}

Then it can be used anywhere provided a MonoBehaviour is used to start it like so:
StartCoroutine(Utils.DelayAction(() => Debug.Log("Delay completed"), 5f);

winged ridge
#

Ooh that I like

molten vortex
#

How could I smoothly zoom a camera in and out? I have this so far:

void ZoomCamera()
    {
        float zoom = zoomAction.ReadValue<float>();
        if (zoom != 0)
        {
            offset -= zoom *  zoomSpeed;
            offset = Mathf.Clamp(offset, 2, 100);

            float positionDelta = offset - currentPosition;
            
            
            
            // camera.transform.Translate(new Vector3(0, 0, -positionDelta));
            currentPosition += positionDelta;

            float velocity = 0f;

            camera.transform.localPosition = new Vector3(0, 0,
                Mathf.SmoothDamp(camera.transform.localPosition.z, currentPosition, ref velocity, 0.2f));

        }

    }

But neither translate nor the smoothdamp does the trick, and the smooth damp gets rid of any direction too, making it always zoom the same direction.

olive lintel
#

Hi all, weird question, and I have no idea which channel to put this but I've made a custom terrain tool and I'm having trouble with it. when I apply a lot of add height to terrain as I've done here, strange ridges appear to form. Even though I'm simply raising each height map point by a generic value, relative to its distance to the tools selection point. Anyone know what might be going on? also if anyone has some resources they could point me to for a terrain smoothing algorithm I'd greatly appreciate it.

winged ridge
#

so stupid question...Are they actual physical ridges or is it an illusion caused by the grid..

#

it could also be brush settings

olive lintel
#

thats why I showed 2 screenshots

winged ridge
#

okay, just checking because that many lines starts playing with my vision sadly... but it could be a brush settings issue where the hardness of the brush is affecting the height its raised to and leaving behind clear borders

olive lintel
#

you mean the strength curve for the brush?

#

this occurs mid way through the brush while it interpolates between strengths

#

I tried increasing the resolution of it 2x over but it hasn't fixed it

#

its most noticable in corners

winged ridge
#

Ill have a look at what Unity calls it, but generally a brush has a feather at the end so it doesnt offer a solid cut, the brush patterns you see have different shapes, one of them is a solid circle, that has no feathering, as an example

olive lintel
native orbit
#

Am I able to get help here?

olive lintel
#

like if someone else has built something like this and ran into this issue

olive lintel
winged ridge
#

oh i thought it terrain tool issue, could be an issue with the calculations between the tris

winged ridge
olive lintel
native orbit
winged ridge
#

it is looking almost like a Sin wave affect in the ground, whether that helps any, hard to say without code

native orbit
olive lintel
radiant voidBOT
twin pivot
#

and theres a different one for vr chat too but im not too sure what the command for it is

fierce shuttle
magic rapids
#

hello everyone!!
i need help desperately

#

but, not sure if it's okay to dump my whole code here?

opaque burrow
#

!code

radiant voidBOT
magic rapids
#

wait

#

while writing, i thought about it, and i might have the solution to my own problem
edit: nevermind, still have the problem

shy sinew
#

I've been impossibly stuck for so long on trying to get a capsule to move in 3d space XD

opaque burrow
#

We are the best rubber ducks sometimes 🙃

magic rapids
#

Problem:
In my 2D game, I need my player to move along in sync with the camera. The camera scrolls to the right using SmoothDamp, and writing to transform.position, so putting the player as the camera's child won't work, it'll break the rigidbody physics (I tried that).
So, in this code, I'm trying to move the player to the right by getting the currentVelocity which is used in the camera's script, in the SmoothDamp thing. I'm writing that to rb.linearVelocity, and it works fine for the horizontal movement, but the vertical movement doesn't work so well. The player goes way up, very fast.
I know for sure that it's not because of the gravity function, nor the jumping, I tried commenting them out to see if they're causing the issue.
I think the issue is that I'm adding rb.linearVelocityY in Scroll() into the equation, which makes it build up in FixedUpdate and go very high very quickly. But then I'm not sure why the same thing but with the horizontal movement works well.

Code:
https://paste.mod.gg/slwxxrrdedyq

midnight plover
#

BlazeBin - slwxxrrdedyq

cunning rapids
#

Guys, is it good practice to keep all variables of an object that may affect the player controller in a single script as a list of variables (not a scriptable object, but monobehavior), where the object might reference said script and the player controller can access it?

#

For example, there would be a common WeaponVars script that holds variables like isAiming or isCharging, which any weapon accesses, but the player can also check for these variables via a property

hexed terrace
#

WeaponVars should really (probably) be a scriptable object. It's just easier to manage data. Every time you want a new weapon and to tweak values, no need to load a scene or anything.

But you still need to use that data, which would be this class you're talking about.

cunning rapids
#

I'll give the concrete example I'm working on rigth now

I have a weapon swap system that swaps between different weapons in a list

Said script has a property to check for the MonoBehavior script WeaponVars

The player controller references the WeaponSwitch script and then uses the property to check for specific states of certain weapons

Etc.

#

Idk how I can have the same effect with an SO

midnight plover
#

You can think of it like your runtime monobehaviour is the handler that serves the data to whoever needs it, but the data itself should be separated and managable for example through SOs. You can still have a list of SOs in your inspector or load all weapons from a folder or addressable system or what not

polar dust
#

WeaponVars could just be its own class, if its only holding data for the Weapon : MonoBehavior

cunning rapids
#
public class WeaponVars : 

What do I put after the colon?

polar dust
#

you dont need to put anything there

cunning rapids
#

Ah, so just a regular class

#

And then I couple the Weapon Script to this WeaponVars class?

polar dust
#

It depends if youre making it a scriptable object or not, if you are then WeaponVars would be the SO and then you make a variation of that object with the data inside it

cunning rapids
#

If WeaponVars is an SO, then how can I access said data of the current, particular weapon I'm holding via the player controller?

#

I can also hold general, shared data in an SO, but I specifically mean variables that affect the player controller

#

For example, when charging up a railgun, I want it to slow down the player

balmy vortex
#

hey so like how do you get the position of another object in unity?

cunning rapids
cunning rapids
#

You assign the other object in the inspector and then it prints its position in the console

keen dew
cunning rapids
#

If you want the general reference you just use

otherObject.position

Or if it's the current game object, just

transform.position
hexed terrace
hexed terrace
weak cedar
#

How do I horizontally stretch objects under a vertical layout group

grand snow
#

enable force expand width?

#

or use layout element with flexible width larger than 0

weak cedar
grand snow
#

the layout group has to be controlling width too

#

then flexible/preferred/min sizing works

lusty star
#

just wanted to share that as i keep learning i keep understanding that i still know nothing what the hell is a constructor 😭

weak cedar
lusty star
#

like i thought when i learnt about playerprefs & like inheritence OOP and like was "yeah im good now" stuff keeps popping out :(

weak cedar
weak cedar
winged ridge
lusty star
#

why does "this" changes the script from not being a parameter

weak cedar
#

With “this”, you are referring to the script in MyClass

winged ridge
#

this. Says this particular object the script is attached to, it's technically defunct.. unless you write a variable with identical name, in which case this. Can differentiate between them

weak cedar
#

If that confuses you just name parameter _script and write “script = _script;”

lusty star
weak cedar
#

Yea

lusty star
winged ridge
#

This site helps a lot

#
lusty star
# weak cedar Yea

thank you im last confused now but i think i need to continue the state machine tutorial to understand more

lusty star
winged ridge
#
private int x = 1;
public int Example(int x)
{
return this.x = x;
}

If you call the method Example() with the int value 7 so Example(7) it would make the prior int of 1 become the 7
#

Very rough example done quick on phone

winged ridge
#

Lol yes corrected it when I saw it

weak cedar
#

0 height

winged ridge
#

You can make the input fields have a component that overrides the layout group I'd have to double check it's name

midnight plover
#

LayoutElement its called

winged ridge
#

Thank you, saved me loading up my laptop

lusty star
winged ridge
#

generally not needed... Avoid naming variables identically

#

It's a left over from an old version where it was needed

lusty star
weak cedar
#

Ok I checked everything but “Control child size - height” works now somehow

lusty star
#

lemme actually type what the tutorial has given me so far

#

    public EntityState(StateMachine stateMachine)
    {
        this.stateMachine = stateMachine;
    }```
radiant voidBOT
lusty star
#

but yeah i still dont get why would i

#

nevermind i think i figured it out

#

so like i want to move to diffrent states, i just type the parameter of the state and it changes the...

#

yeah brains fucked, ill just follow the tutorial

#

well thanks everybody

rough sluice
#

Will we need paid hosting services to make our Unity game online multiplayer?

#

Can we host our Unity game globally?

keen dew
#

Most multiplayer services have a free tier that's good enough for 99%+ projects

cunning rapids
midnight plover
cunning rapids
#

Yes, but the switch script accesses the weapon stats as a property in which the player controller access it

#

Idk how the weapon switch script can access the SO that the current weapon is using

winged ridge
#

From that code it is saying that ClipSize is set as the variable data it got from weaponSO.clipsize

cunning rapids
#

It's an example, not my actual setup

#

I'll send it

winged ridge
#

What are you wanting it to do

cunning rapids
#

Here is the weapon stats mono script

#

Applied to the weapon

winged ridge
#

Okay so in the sniper hitscan data scriptable object is the variable you want public? If so just do data.clipSize

cunning rapids
#

No, give me a sec

#

Switch weapon property access (for the current weapon):

  public WeaponVars currentWeapon
  {
      get
      {
          if (weapons == null || weapons.Count == 0) return null;
          var weapon = weapons[selectedWeapon];
          return weapon != null ? weapon.GetComponent<WeaponVars>() : null;
      }
  }
#
[Header("Weapons")]
public SwitchWeapons activeWeapon;

In the Player controller, accessing the current weapon stats

#

I hope this makes sense

#

It works, but I really doubt this is the cleanest implementation

cunning rapids
midnight plover
#

Yeh its a weird mix of Sniper SOs but weapon vars is a monobehaviour but written like a class without any functionality. Why not make the vars SOs too and just drag them in your sniper script?

cunning rapids
#

Because the weaponswap script would have to access the SO the current weapon is using, then turn it into a property, then the player controller has to access that property

#

And I have no idea how to do that

#

I'll try to, see where it gets me

midnight plover
#

You access it like any other script. Instead of WeaponVars being Monobeavhiour, you just make a scriptbale object as type, thats it. Create an asset, drag drop it there

cunning rapids
#

Oh wait you can do that?

#

I thought you can only drag and drop if it was mono

#

Into the inspector, that is

#

As a component

midnight plover
#

You can drag drop anything in the inspector, no matter the class type as long as your reference field is declared as the correct type

#

Just to be aware of the issue with SOs. In edit mode, if you change something on the SO via script, lets say, ammunition or something, it will persist. But if you change runtime values in a build on those SOs, they get reset when restarting your game to their exported values from editor

cunning rapids
sour fulcrum
cunning rapids
#

Uhh

ArgumentException: GetComponent requires that the requested component 'HitscanData' derives from MonoBehaviour or Component or is an interface.
UnityEngine.GameObject.GetComponent[T] () (at <54724222b7684530a2810ae1eac94ec7>:0)
SwitchWeapons.get_currentWeapon () (at Assets/Scripts/GunScripts/SwitchWeapons.cs:20)
Q3Movement.Q3PlayerController.Update () (at Assets/Scripts/QuakeController/Q3PlayerController.cs:124)

midnight plover
cunning rapids
#

So what do I do?

midnight plover
#

Sniper.weaponvar.yourValues

cunning rapids
#

SwitchWeapons.cs and Sniper.cs are different mono scripts

midnight plover
#

show them please

cunning rapids
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;

public class Sniper : MonoBehaviour
{
    public Camera viewmodelCam;
    public HitscanData data;

    void Update()
    {
        Aim();
        SmoothFOV();
        if (Input.GetButton("Fire1"))
        {
            if (data.releasedButton)
            {
                data.holdTime += Time.deltaTime;
                data.isCharging = true;
                if (data.holdTime >= data.chargeUpTime)
                {
                    Shoot();
                    data.holdTime = 0f;
                    data.shotFired = false;
                    data.releasedButton = false;
                }
            }
        }
        else
        {
            if (data.isCharging && data.holdTime < data.chargeUpTime && data.releasedButton)
            {
                Debug.Log("Charge canceled");
            }
            data.holdTime = 0f;
            data.isCharging = false;
            data.releasedButton = true;
        }
    }

    void Shoot()
    {
        if (data.shotFired) return;
        if (Physics.Raycast(transform.position, transform.forward, out RaycastHit hitInfo, data.range, data.hitLayers))
        {
            Debug.Log("Hit " + hitInfo.collider.name);
            data.shotFired = true;
        }
    }

    void Aim()
    {
        if (Input.GetButtonDown("Fire2"))
        {
            data.isAiming = true;
        }
        if (Input.GetButtonUp("Fire2"))
        {
            data.isAiming = false;
        }
    }

    void SmoothFOV()
    {
        float targetFOV = data.isAiming ? data.zoomedFOV : data.normalFOV;
        viewmodelCam.fieldOfView = Mathf.Lerp(viewmodelCam.fieldOfView, targetFOV, data.smoothSpeed * Time.deltaTime);
    }
}

Sniper.cs

rough sluice
midnight plover
#

Would be great, if you could use paste websites for those large blocks !code

cunning rapids
cunning rapids
cunning rapids
midnight plover
#

Ah, so the problem now is, that you have a single class for sniper which inherits from nothing.

fleet coral
#

Hey everyone! 👋 I’m completely new to C# and Unity, and I’d really like to learn how to make a simple block move around and look around, like a basic player controller. Does anyone have any good beginner-friendly links or resources to help me get started? Thanks a lot! 🙏

keen dew
midnight plover
#

I am just wondering, where does hitscandata come from?

#

HitscanData seems to be a type but weaponvars is also its own type?

cunning rapids
cunning rapids
cunning rapids
midnight plover
cunning rapids
midnight plover
#

You inherit

cunning rapids
#

Makes sense

cunning rapids
#

I'll do that rn, thanks

midnight plover
#

yw 🙂

cunning rapids
#

And any new weapon behavior I can just add another class?

winged ridge
#

There's a few ways you could do that, how many weapon types do you want

midnight plover
#

If you really need too. Depends on your weapons tbh.

cunning rapids
#

If there are many weapons I can just make a new script so it doesn't get too convoluted I'm guessing?

midnight plover
#

You could have another category of Firearms, Swords and whatever. This really depeonds on your game design

cunning rapids
cunning rapids
midnight plover
#

The more they share, the easier it gets for you to develop and expand

winged ridge
#

So put the types in an enum and a switch case, with each case having a method.. OR do a weapon class and then in that class Weapon sniper = new Weapon(){ edit variables here}

midnight plover
#

You should really write down, what your types are, what they share and what not, what you need your other objects to rely on those weapons and so on. try not to develop while conceptualizing your game, because that can easily run into a big pile of spaghetti code 😉

cunning rapids
#

Why can't I modify inhereted/child classes in the inspector?

timber tide
#

Whatcha mean? If you extended Weapon then use the correct component.

grand snow
cunning rapids
frosty hound
#

You can't have two monobehaviours in a single script. Make two.

hexed terrace
#

also, setup your visual studio correctly

grand snow
#

yea unity gets confused and it causes problems

hexed terrace
#

!vs

radiant voidBOT
# hexed terrace !vs
Visual Studio guide

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

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

cunning rapids
#

It isn't a mono, it's an inheritence

frosty hound
#

Okay 🤷‍♂️

grand snow
#

(hint: it is)

cunning rapids
hexed terrace
#

it inherits from a monobehaviour... making it ... a... monobehaviour

cunning rapids
frosty hound
#

You put the DefaultSniper component on your object, and you modify the values on that component, which will include anything in its own class and any in the inherited classes.

half lantern
#

Hi, in this code, I did a server check, yet the code still gives me a "NotServerException: Only server can change visibility error". How is that possible?
public void ChangeVisibility(List<ulong> clientsVisible)
{
if (!IsServer){ return; }
List<ulong> aliveClients = PlayerManager.Instance.GetAliveClients();
foreach (ulong client in aliveClients)
{
NetworkObject playerNetObj = PlayerManager.Instance.GetPlayer(client).gameObject.GetComponent<NetworkObject>();

        if (!clientsVisible.Contains(client))
        {
            playerNetObj.NetworkHide(OwnerClientId);
        }
        else
        {
            playerNetObj.NetworkShow(OwnerClientId);
        }
    }
}
stiff birch
half lantern
#

do you just put !code before the code

stiff birch
#

!code

radiant voidBOT
half lantern
#

oh ok

stiff birch
cunning rapids
half lantern
#

lol

hexed terrace
hexed terrace
frosty hound
#

I don't understand the context. You can have a Weapon HeldWeapon property on your Player which can be any object that has a component which has or inherits from Weapon

#

You can even have a list of them that you can switch between.

half lantern
#

so does anybody know why its giving me a notserverexception when im checking for server

#

its running on the host

cunning rapids
cunning rapids
hexed terrace
#

Make a class in its own file called Weapon.cs - public class Weapon : MonoBehaviour
Make another class in its own file called DefaultSniper.cs - public class DefaultSniper : Weapon

Declare on your player(?) public Weapon currentWeapon;

Either of these two classes can be assigned to currentWeapon

frosty hound
#

Sure, you can have a weapon handler component on the player that deals solely with that. It can have the properties or list of weapons in the player's inventory.

stiff birch
half lantern
#

its hiding a player object of a different player from the owner of the script

half lantern
stiff birch
half lantern
#

dw guys i just solved it, it was because I forgot to skip the loop when the client variable was equal to the OwnerClientId, so it was trying to hide the player object from the player who owned it i think

#

idk why that gave not server exception tho

cunning rapids
rough sluice
cunning rapids
frosty hound
#

Personally, I would have a PlayerController_Weapon component on the root Player object where the main brain PlayerController is.

#

But that's entirely up to how you want to organize things.

cunning rapids
#

Would that be an inheritence of the player controller that handles weapon switching?

frosty hound
#

Nope, just a component that the PlayerController holds a reference to.

#

When I've done complex controllers, I would have

PlayerController
PlayerController_MoveComponent
PlayerController_AnimateComponent
PlayerController_InventoryComponent
...etc.
#

They would just sit on the same root, and handle their logic. However, anything external only interacted with the PlayerController, which decided if things would be passed to those relative components for handling.

cunning rapids
#

Would there be any advantage of it being an inherited class over mono?

frosty hound
#

Putting the weapon handling logic on a separate object entirely that is on your player is fine, as long as the player can check it for whatever it needs such as if the currently held weapon is charging so that it can factor that into its calculated velocity this frame.

cunning rapids
#

Just to clarify, "on your player" means inherited?

hexed terrace
#

"on your" generally means on the game object, not code

cunning rapids
#

Ah, I see

cunning rapids
shell sorrel
cunning rapids
shell sorrel
#

things like weapons i like to reference via a interface types, and keep functionality that is possibly shared between many weapons as just regular objects each weapon can have there own instance of

gentle trellis
#

I've assigned the originalmaterial, newmaterial and the spriterenderer correctly

agile pagoda
#

I have a general question about DOTS

Ive got my system setup and I can do 100k + objects with scripts, shadows and I get 100+ fps

However im abit confused on what the best practise is to set it up without needing so many different scripts and this much code.

Does anyone have any good references or best/good practice examples?

#

I could link my code if anyone wants to take a look

timber tide
agile pagoda
#

ty 😄

umbral bough
#

Hey, I am looking for the best approach when it comes to "storing" settings for a monobehaviour.
I basically wanna be able to have a field in my class or scriptable object that would hold these and allow editing in the inspector, just like if you had the component attached to the object, and then copy those settings to the actual component when needed.
To give a bit more context, I am working on an audio manager and want to support Steam Audio.
The Steam Audio Source component is quite large and has a custom inspector, duplicating the entire thing just to add the [Serializable] attribute on top of that duplicate class seems very unreasonable, so I was wondering if somebody has a better suggestion for me.
Please @ me and thanks in advance!

timber tide
queen adder
#

My player controller only uses Rigidbody.addForce in the Update() function and the physics system is set to run per frame. For some reason, moving makes the screen look very choppy. If I just rotate the camera it's fine.

#

framerate is also locked at 165fps (monitor refresh) so I don't think that's the issue

timber tide
umbral bough
# timber tide Sounds like you should just use scriptable objects, no?

I am already using a scriptable object, I am just not sure how that would solve my issue.
I am looking to basically be able to just edit all the SteamAudioSource settings within that scriptable object, like if you literally attached that component to the SO but not quite, it's supposed to be a field in that SO.
I am basically trying to get the component seen in the picture, or at least all its contents, on that SO.

timber tide
#

So you basically just want this mono here to become a SO of data?

umbral bough
timber tide
#

If you just want the fields I'd open the class and copy paste it onto a SO class, and if you want some of that serialized data that's set then open up unity's yaml and copy it over

umbral bough
timber tide
#

Idk, only thing I can think of is just edit the steam audio source class to accept the SOs and just wiring it back together

umbral bough
#

ye, sadly there doesn't seem to be a solution to what I'm looking for :/

#

guess I'll just go the copy paste route, thanks either way

jaunty coyote
#

public void Setup(List<Building_JSON> oldBuildings) { print(oldBuildings.Count); allBuildings.Clear(); print(oldBuildings.Count); }
How is it possible that oldBuildings returns 1, after clearing an unrelated list its back to 0

sour fulcrum
#

is that an unrelated list

jaunty coyote
#

yes, so how is it possible that that happens

#

i cant wrap my head araund it

sour fulcrum
#

are you sure its an unrelated list

jaunty coyote
#

100%, just added it

#

as you can see is local

#

it would get referenced later on, passed to functions but as it is right now i cant do that

#

the setup gets called only once, so no way to be overriden

sour fulcrum
#

i might be missing something but the only way i can see that code printing 1 then 0 is if allBuildings and oldBuildings are both the same list

polar acorn
jaunty coyote
#

they are the same type but not the same list

naive pawn
polar acorn
#

Where do you call Setup? What do you pass to it?

naive pawn
#

try logging oldBuildings == allBuildings, then we'll know for sure if they're really unrelated

polar acorn
#

Lists are reference types. If you pass allBuildings to this function, then both allBuildings and oldBuildings refer to the same list

jaunty coyote
polar acorn
jaunty coyote
#

Looks like it

naive pawn
jaunty coyote
#

ooh, i thod that means they are the same thing

#

so currently we dont know much?

naive pawn
#

"sets it to true" means = true, an assignment

naive pawn
jaunty coyote
#

which they shouldnt be

#

i think

naive pawn
#

then work backwards - check the thing that's calling Setup, see what it's passing in

jaunty coyote
#

found the solution

#

allBuildings = new List<Building_JSON>(); print(oldBuildings.Count); foreach (Transform t in buildingHolder) { Destroy(t.gameObject); }

#

looks like if i just unbind the allbuildings list from the oldbuildings list, it works

#

thanks for your time, have nice rest of the day

naive pawn
#

like, having them be the same list isn't really an issue tbh

bleak hull
#

ok s

#

basiccaly

#

i uh

#

try to make game today

#

but i t like broke

#

so i need help

#

i tried following this tutorial:

#

but at the timestamp with the RigidBody2D thingy

#

it doesnt highlight cyan and just says this when i try to run the code

slender nymph
#

configure your IDE 👇

#

!ide

radiant voidBOT
polar acorn
bleak hull
#

shut

#

😡

polar acorn
bleak hull
#

i hate you

#

🥀

slender nymph
bleak hull
#

please say you arent being for real

slender nymph
#

give it a read and stop spamming

bleak hull
#

i am not spamming

#

gng

#

i am asking question

slender nymph
#

11 messages for a single thought is spam

urban sluice
#

Is using netcode for entities a good idea for an fps game with max like 10 players at once? I am not really worried about performance since the game is really small scale and graphically undemanding, but I am considering netcode for entities because of the premade prediction for it and unity also recommends it. Netcode for entities also seems really challenging, even though I have coded for around a year on unity so I am a bit scared, do I have reason to be? Would making a prediction system for game objects be easier and simpler to maintain?

bleak hull
#

i wish i knew

slender nymph
slender nymph
bleak hull
#

i aint reading allat

#

you aint a mod mate

slender nymph
#

no but <@&502884371011731486> are

bleak hull
#

really

#

didnt know that

fickle plume
#

@bleak hull You've been made aware of server rules, follow them and don't spam.

bleak hull
#

bro are you fr

#

i just asked for help

#

😭

fickle plume
#

properly installed IDE will point out those errors and suggest fix.

bleak hull
#

oh crap i didnt see that

#

whoopsie

#

how do i do that? im a idiot

#

oh wait

#

i have visual studio insatlled

polar acorn
bleak hull
#

thats what i

#

please

#

😭

#

shouldnt it already be updated

#

whateer ill just try it

slender nymph
#

jesus christ stop spamming. finish a thought before sending your message

polar acorn
#

Why do you take twelve messages to say absolutely nothing. Just take like half a second to think the whole sentence through before sending a message.

frank fossil
#

He is probably just young we all did that before (but i agree)

bleak hull
#

i aint young, just no idea what im doing

#

i started unity today

polar acorn
polar acorn
bleak hull
#

i dont like typing with punctuation

frosty hound
#

@bleak hull If you're going to keep waterfall typing, you're going to be muted for spam. You can stop hitting your enter key so much, thanks.

bleak hull
#

i have made a severe, and continuous lapse of my judgement and do not expect to be forgiven. i am simply here to apologize.

fickle plume
bleak hull
#

alright ill try

#

i have terrible focus but ill still try, thanks

fickle plume
#

Still, a proper course will cover much more ground.

urban sluice
slender nymph
#

netcode for gameobjects is similar to netcode for entities, it's just the one built for the gameobjects workflow

urban sluice
slender nymph
#

#1390346492019212368 should be where you direct your networking related questions. it is not a beginner topic.

slender nymph
bleak hull
#

gaaaaaaaaaaaah

#

ok

#

why would it be outdated tho, i literally installed it today

slender nymph
#

nobody said it was outdated

bleak hull
#

why would i need to update it then?

slender nymph
#

you need to configure it

fickle plume
#

follow the manual install guide to make sure you have everything configured properly

bleak hull
#

mkay

slender nymph
bleak hull
#

YOU LEGEND

#

IT WORKED

#

I LOVE YOU BOXFRIEND

#

i will never doubt you again

fickle plume
#

Did you have 2019 installed already? It should've have prompted you to install 2022 one in the Hub

#

You might want to upgrade to 2022 it has many performance improvements.

hexed nymph
#

Hello guys! Soooo I was using the "old" Input System (using like "Input.GetKey(Keycode)" and so) and in the same script I've created the "jump" action when you press the jump key and "cancel jump" when you realease the jump key when you're jumping. Then yesterday I wanted to make the android port to the game and so I decided to switch to the new input system but when I tried the jump method it didn't work, the high was like the double as before and didn't even recognize the key when pressed or realeased, though sometimes it acted like normal, its very inconsintent.

I'll send the paste.mod link

random lodge
#

Is there a way to code an animation to 50% transparency? I looked at the animation properties and the button is disabled.

#

Would like to keyframe it but seems it's not allowed

shell sorrel
#

you can key frame the color of a sprite

#

can keyframe its transparency that way via the alpha channel of color in code alpha is done the same way

hexed nymph
random lodge
#

I'll switch to unity-talk since we're on the animator

bleak hull
#

oh my god

#

WHYYY

slender nymph
#

clear the console and find out why

bleak hull
#

alr

#

wut

random lodge
#

might be able to double click that to see where it is in your code so you can show it

slender nymph
# bleak hull

it's pretty self explanatory, you cannot assign to Vector2.up. you can only use its value

shell sorrel
# bleak hull

in your code somewhere you have Vector2.up = someOtherTHing

bleak hull
#

after that its 10;'

#

10;

slender nymph
#

=

shell sorrel
#

second = shopuld be a *

bleak hull
#

ah

#

omg it worked

#

you guys are geniuses bro

shell sorrel
#

Vector2.up is the same as new Vector2(0, 1) the * 10 multiplies it so it becomes (0, 10)

bleak hull
#

alright

#

thanks

random lodge
#

the underlines are pretty reliable at telling you there's a big problem

bleak hull
#

righteyo

chrome apex
#

If I have a player that is horizontal and needs a torso collider, but also hand and head colliders (however, only the torso one should stop movement), how should I make it?

For example, char controller is easy but it can only be vertical.

Should I go kinematic rb and capsule/box/whatever cast movement?

What about trying to rotate in a space which has no room to rotate?

winter dirge
#

Does anyone know what might be happening?
I'm making my first project and I followed a tutorial

slender nymph
#

not without relevant code

#

!code

radiant voidBOT
winter dirge
winter dirge
# slender nymph not without relevant code

Sorry, this is my camera script:

using UnityEngine;

public class PlayerCam : MonoBehaviour
{
    public float sensX;
    public float sensY;

    public Transform orientation;

    float rotationX;
    float rotationY;


    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
    }

    void LateUpdate()
    {
        // Mouse input
        float mouseX = Input.GetAxisRaw("Mouse X") * Time.deltaTime * sensX;
        float mouseY = Input.GetAxisRaw("Mouse Y") * Time.deltaTime * sensY;

        rotationY += mouseX;
        rotationX -= mouseY;

        rotationX = Mathf.Clamp(rotationX, -90f, 90f);

        // Rotate camera and orientation
        transform.rotation = Quaternion.Euler(rotationX, rotationY, 0);
        orientation.rotation = Quaternion.Euler(0, rotationY, 0);
    }

}
slender nymph
cosmic quail
winter dirge
winter dirge
slender nymph
#

shit tutorial

cosmic quail
winter dirge
#

Maybe

slender nymph
#

it is. not only is it just copying a brackeys tutorial literally line for line, but it also includes that infamous deltaTime mistake that has caused countless indie games to have stuttery camera controls

#

also pretty much 100% of these "X in Y minutes!" videos is garbage because they don't typically bother to teach why you would do something a specific way, they just tell you how to do something and expect that to actually teach anything other than reliance upon tutorials

polar acorn
#

If a tutorial advertises itself based on its brevity rather than it's completeness, that means its target audience is people who are looking for a quick fix without actually learning anything, and therefore they don't actually need to ensure the video is correct because those aren't the types of people to ever actually implement anything.

Basically, a tutorial saying "In X Minutes" is the youtube equivalent of bright primary colors on a jungle frog.

mild furnace
#

Yo my project is being ravaged by auto formatting after updating vscode

Is there a way I can get it to stop turning

if(true) {
          
}

into

if (true)
{
  
}

every time I press enter?

slender nymph
#

that would be in vs code's settings, so not really unity related. but also the latter is the standard for the language

rich adder
mild furnace
#

Eh i've put 4k hours into this project, not gonna change formatting now

mild furnace
#

this is obnoxious, i cant work in larger methods without things rearranging

rich adder
polar dust
mild furnace
#

I dont want any format features other than preserving the indent, auto wrapping parenthesis etc

#

This is stupid lmao

molten vortex
#

How can I create a script that is always running but isnt tied to a specific object? I want to detect mouse clicks to select objects in the scene but I don't know how to activate such a script

slender nymph
#

unless you plan to leverage the EventSystem manually by using it to raycast into the scene each time the mouse is clicked, you would be better off creating a component that implements the relevant event system interfaces (such as IPointerDownHandler for detecting a click on an object) and put that component on the objects you want to be clickable

molten vortex
#

could i have a global variable somehow to store what object was last selected then?

slender nymph
#

i mean, sure. but that sounds like it may not be all that helpful. of course you need to actually explain the end goal of all this in order to determine the best course of action

molten vortex
#

I want something kind of like the sims where you select a sim, or an object, then have options or can send it somewhere

rocky canyon
#

not sure why not having a gameobject that tracks that in ur scene at all times..
like a "Manager" type script.. could give it the reference and even have it DDOL so it presists from scene to scene

cosmic dagger
buoyant haven
#

Hey yall. How can I load all the addressables with one label at once in Unity 6? There was a method Addressables.LoadAssetAsync<GameObject>("Label", null, true); and now LoadAssetAsync only takes one argument

slender nymph
#

hint: check the docs

#

you may also find that your assumption of using LoadAssetAsync to load more than one asset in the past was incorrect

buoyant haven
# slender nymph hint: check the docs

Thanks. I am looking at docs. I am new to all this. In "Load multiple assets" section there's a code:

            keys,
            addressable =>
            {
                //Gets called for every loaded asset
                Instantiate<GameObject>(addressable,
                    new Vector3(x++ * 2.0f, 0, z * 2.0f),
                    Quaternion.identity,
                    transform);

                if (x > 9)
                {
                    x = 0;
                    z++;
                }
            }, Addressables.MergeMode.Union, // How to combine multiple labels
            false);

however, when I try this, I am getting error and method signatures that not even close to the exampleon Unity website (screenshot)

slender nymph
#

notice how the method in the docs is different than the one you are attempting to use

buoyant haven
molten vortex
#

When using a cinemachine follow camera set to orbital follow, how can I change the input scheme to rotate the camera? All I want to do it make it so it only rotates when right mouse is held but eveyrthig I've found online is outdated

timber tide
#

Figure out which property rotates it in the inspector then find how to call it in your script

dark tapir
#

I Have a Question How can I force rotation of an object in a positive coordinate? And do not reverse the negative so that it is 0 to 360 and then return to 0

quartz jay
#

Does anyone know how to fix positioning with an object when the scaling on an object is weird?

#

For example I scaled my models arm size and the script that uses my IK target to go on the controller is wonky when I scale it.

#

I am wondering how I can fix this issue?

wintry quarry
wintry quarry
dark tapir
#

This Is My Code

#

using UnityEngine;

public class DiaNocheLatitud : MonoBehaviour
{
[Header("Velocidad de la Rotación del Sol (día)")]
public float Ve = 10f;

[Header("Objetos de Referencia de Latitud")]
public GameObject Jugador;
public GameObject Latitud50;
public GameObject Latitud26;

[Header("Objetos de la Luz Solar")]
public Transform PivoteSol;
public Transform LuzSolar;

private float currentAngle = 0f; 
public float AnguloForzado { get; private set; }

void Start()
{
    InvokeRepeating(nameof(Ac), 0f, 0.2f);
}

void Update()
{
    if (LuzSolar == null) return;
    currentAngle += Ve * Time.deltaTime;
    if (currentAngle >= 360f) currentAngle -= 360f;
    LuzSolar.localEulerAngles = new Vector3(0f, currentAngle, 0f);
    AnguloForzado = (LuzSolar.localEulerAngles.y + 360f) % 360f;

    //opcional: debug
    Debug.Log($"Ángulo leído del transform (forzado 0-360) = {AnguloForzado}");
}

void Ac()
{
    if (Jugador == null || Latitud50 == null || Latitud26 == null || PivoteSol == null) return;

    float distancia50 = Vector3.Distance(Jugador.transform.position, Latitud50.transform.position);
    float distancia26 = Vector3.Distance(Jugador.transform.position, Latitud26.transform.position);
    float distanciaTotal = Vector3.Distance(Latitud50.transform.position, Latitud26.transform.position);
    float factor = distancia50 / distanciaTotal;

    float latitud = Mathf.Lerp(73f, 49.5f, factor);
    PivoteSol.localEulerAngles = new Vector3(latitud, 0f, 0f);
}

}

dark tapir
fast heron
#

(sorry don't know if my last message sent)

is there a preferred way to do a "deep copy" of an object in unity? say I had a class representing a tetris piece like so:

public class NewPiece
{
    public Tetromino Tetromino;
    public Tile Tile;
    public Vector3Int Position;

    public Vector2Int[] Cells;
    public Vector2Int[,] WallKicks;

    public int RotationIndex = 0;

and i wanted to make a deep copy of it, i.e one that's a duplicate of the original but whose fields aren't just references to the original such that changes to the copy WON'T reflect in the original, how would I do that?

#

stuff on the internet says to serialize the object into json and then immediately deserialize it

#

that seems a bit hacky though, does unity have a built-in solution or something?

rugged beacon
#

is there any way to avoid k___backingfield while keeping the field auto property with json nutiltiy?

cosmic dagger
neat bay
#

does anyone know a way I could create a special depth buffer that draws transparent object's depth, and increase their depth based on theri alpha?

#

in URP?

midnight plover
neat bay
#

yeah, I need it for blending transparency on a volumetric fog shader

#

is there a way to do it?

midnight plover
#

Shouldnt the volumetric shader already cover that?

neat bay
#

I'm raymarching the depth buffer and testing density along the way, but because transparents dont write to the depth buffer, the ray marches through the objects that are in the transparent queue

obsidian sandal
#

does GameObject.Find find child objects?

teal viper
teal viper
obsidian sandal
#

how come it's telling me it's destroyed then

neat bay
teal viper
neat bay
#

or render a seperate depth buffer that draws for only transparents and base the distance on the alpha for each pixel?

neat bay
neat bay
#

ill do that next time

teal viper
neat bay
#

i dont really need anything more than one transparent object in front of another

#

and if i do id jsut use alpha clipping

neat bay
teal viper
neat bay
#

yeah i figured as much 😮‍💨

#

are there any other approaches? i just never bothered to learn the scriptable render pipeline tbh cause it was a little overwhelming

#

or is using the srp the only way to do this

teal viper
#

You can do it in any render pipeline. It's just gonna be different.

#

SRPs(urp/hdrp) mainly use render graph api for that now.
Builtin was mainly doing it via the shaderlab AFAIK.

neat bay
#

im using URP, but i just neverr bothered to learn how to make custom render passes & features

neat bay
#

also does that mean learning the SRP is the only way to achieve creating this custom transparency depth buffer?

teal viper
teal viper
balmy vortex
#

hey so like how do you check if an object/collider is touching anything?

low goblet
#

I'm still somewhat new to Unity, but I've been starting to find that Unity's object pool API isn't really enough for me. Is there much of a downside to creating my own objectpooling system?

neat bay
neat bay
barren vapor
#

Was just showing that googling should be your first reflex

neat bay
balmy vortex
barren vapor
grand snow
#

all physics "messages" have a 2d version

neat bay
barren vapor
#

if you don't know it -> google, no source or can't find it -> AI/asking others

balmy vortex
#

what am I supposed to put in the (collider) arguement in the function btw?

#

like obviously its for the collider of the object but how do I grab it to plug it into the function?

grand snow
#

no the arg is the collider it HIT

neat bay
#

"Collider" gives you the collision data of the gameobject you've hit

polar dust
sour fulcrum
grand snow
barren vapor
#

Just don't blindly copy-paste

#

Plus, basically everything already has been documented on google

balmy vortex
sour fulcrum
#

Just means your not looking through your search engine results well enough 😄

grand snow
barren vapor
sour fulcrum
#

No thanks I can search myself 😄

balmy vortex
#

why are we recommending AI to people again?

low goblet
late badger
balmy vortex
late badger
low goblet
#

no rb, and you probably don't need 2 sphere colliders

lunar coral
#

!code

radiant voidBOT
lunar coral
#

hello,I'm trying to make bots for my game but they dont work properly, 1: they don't always hit the player, 2: animations don't work properly

#

here are the 2 scripts managing everything

#

the Dieass() function is getting called in another script when the bot dies

silver fern
#

define properly

lunar coral
rich adder
rain night
#

can we import old swf assets in unity? (am trying to remake a game from 2011 lol)

shell sorrel
#

no

rocky canyon
#

arrrr!

rain night
shell sorrel
#

so would need to bitmap stuff or try and get it as svg and relie on unity vector graphics importer which is also nowhere near perfect since its a approxmiation what svg's can do using meshes, uvs and textures

elder hearth
#

I have 2(really stupid for my skill level) questions:
**1. **How do scripts communicate via raycast. Like if A shoots a ray and it hits a script called B what method do i call??
**2. ** How do i make it so a text shows up over an object but its different for each objectand it stays there for as long as its in a certain area of the screen? <- Ig you could count this as a sub question of 1

rain night
shell sorrel
shell sorrel
#

no clue what that is, i have not touched flash stuff since the early 00's

rain night
#

I was thinking to build my childhood game for old times sake. oof

rocky canyon
#

could rebuild it without needing to rip anything from antique fileformats

elder hearth
shell sorrel
lunar coral
rocky canyon
#

yup, coulda put a script on each one (the same script w/ a variable u change per each) like a description
ur raycast script would grab that script access its variable and display it somewhere

lunar coral
#

the problem is that he hits the player 15% of the time

shell sorrel
rocky canyon
#

we all were at some point.

rain night
#

guess u are right

#

I do have some img assets tho. Will try to make it work

shell sorrel
rain night
#

its basically a pokemon type game

shell sorrel
#

since even if you could get the as2/3 code out non of it would be translatable in any meaningful way

rain night
#

so I have to comeup with logics myself

silver fern
grand snow
#

you use a debugger to DEBUG logic and inspect values

#

printing to the console is a very small part of debugging and often not enough

lunar coral
#

the problem is with this wait

silver fern
#

if your bot keeps missing surely the aim direction variables cant be right?

shell sorrel
#

or there is a factor they are not considering

lunar coral
#
Vector3 aimDirection = (playerBox.position - firePoint.position).normalized;
        firePoint.LookAt(playerBox.position);
        float radius = 0.6f;

        // raycast + detection
        if (Physics.SphereCast(firePoint.transform.position, radius,  aimDirection, out rayHit, whatIsPlayer))
        {
            if (rayHit.collider.CompareTag("hitbox"))
            {
                rayHit.collider.GetComponent<PlayerHealth>().TakeDamage(damage);
                df.ShowDamage();

            }
```csharp
silver fern
#

is firepoint right? I don't see where you set that

lunar coral
#

the playerBox is the transform of the collider the bot has to hit

lunar coral
#

yea the variables are all correct

silver fern
#

you could also draw a debug ray to make sure the raycast is going in the right direction

shell sorrel
lunar coral
#

and it's going in the right direction

silver fern
#

ah it could be hitting the bots own hitbox

lunar coral
#

or another collider

shell sorrel
#

anything, just log of its hitting and if it is see what its hitting

lunar coral
#

k I'll do that

grand snow
#

you sound like you dont want to fix i)

silver fern
#

he seems to be trying

grand snow
#

anyway I gave my suggestion (debugger)

#

best way to detect silly mistakes and inspect what happens

shell sorrel
#

also firePoint, is that like your gun or something?

lunar coral
#

but sometimes it hits the player

silver fern
#

there must be ground in the way

lunar coral
shell sorrel
#

0.6f is a pretty big radius

grand snow
lunar coral
#

and I'm actually building my game in devlopment build as u suggested me

#

with script debugging options enabled

shell sorrel
#

figure out why, if its hitting ground the radius of hte sphere cast is too big or you are angled down

#

or there is something you do not see that is ground its hitting

lunar coral
shell sorrel
#

its your game, test things

#

figure out if thats the issue, or like debug draw spheres along the path or something

grand snow
lunar coral
#

yeaa im sorry, the thing is I was using raycast and I asked chatgpt, he told me the ray might be too small so I had to test with a big spherecast

silver fern
#

never trust the ai

lunar coral
silver fern
#

it is for everything

naive pawn
#

it's fine for generating filler text tbh

grand snow
#

ray to small haha

lunar coral
#

but finding help isn't always easy

naive pawn
#

genai is the opposite of finding help

silver fern
#

but yeah ray too small makes zero sense

shell sorrel
#

think about your game and what you want to accomplish not waht AI is telling you

shell sorrel
#

there are many reasons to use ray, or reasons to use sphere cast it depends on what you are trying to accomplish

lunar coral
shell sorrel
#

but also think about things like how tall is a bot in your game and how tall is a player

naive pawn
#

it's just a word randomizer trying to be convincing, rather than correct

shell sorrel
#

raidus 0.6 is a sphere with a 1.2m diameter which would easily clip the ground if shot by something the size of a human

polar acorn
lunar coral
silver fern
polar acorn
naive pawn
#

youtube is not the only resource. docs, forums, etc exist

shell sorrel
#

breaking it down into smaller problems, docs and experiments

hexed terrace
#

docs, web search, experimentation, etc

naive pawn
#

and also yeah, you generally don't look for full tutorials

#

you learn and understand simpler concepts and then combine them

lunar coral
#

okayyy

#

I just downloaded reddit, I hope it'll help me

#

I've heard it's a productive forum

silver fern
#

you did what

naive pawn
#

uhhh well i mean that's not wrong, but it's also not super friendly at times, so be aware of that lol

lunar coral
#

in reddit

naive pawn
#

generally reading existing forum posts is sufficient

silver fern
#

well it wont hurt to ask surely

naive pawn
#

it just wastes your own time if it's already been asked

#

forums have search bars for a reason

lunar coral
naive pawn
#

yeah

lunar coral
#

okay

hexed terrace
#

google searches generally bring up Reddit posts if there's something relevant on there already

naive pawn
#

do be aware that searching is also a skill in itself

shell sorrel
#

also break your problme down

#

don't search some broad huge thing, break it into the steps needed to do that

naive pawn
#

sometimes you gotta cast an incantation -site:reddit.com after:2018 before:2022

lunar coral
#

okayy thanks guys

lunar coral
#

it now hits "FPSPlayer" gameobject that's the parent of the hitbox

#

anyway I'll figure out how to do it dw

sage wyvern
#

i need help, i tried to make a sprinting mechanic using everything i learned but now that i've done this once that i press the left shift key it will not go back to normal speed.

naive pawn
#

!ide

radiant voidBOT
sage wyvern
#

VS Code

naive pawn
#

secondly, where are you resetting the speed? (and format it properly please 👇)

#

!code

radiant voidBOT
sage wyvern
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
   public CharacterController controller;
   public Transform cam;

   public float speed = 6f;
   public float sprint= 10f;

   public float TurnSmoothTime = 0.1f;
   float TurnSmoothVelocity;

    Vector3 velocity;
    public float gravity = 9.81f;
    public float jumpHeight = 3f;

    public Transform GroundCheck;
    public float GroundDistance = 0.4f;
    public LayerMask GroundMask;
    bool isGrounded;

    void Start()
    {
        Cursor.visible = false;
    }

    // Update is called once per frame
    void Update()
    {
        isGrounded = Physics.CheckSphere(GroundCheck.position, GroundDistance, GroundMask);

        if (isGrounded && velocity.y < 0 )
        {
            velocity.y = -2f;
        }

        if(Input.GetButtonDown("Jump") && isGrounded)
        {
            velocity.y = Mathf.Sqrt(jumpHeight * -2 * -gravity);
        }

        float horizontal = Input.GetAxisRaw("Horizontal");
        float vertical = Input.GetAxisRaw("Vertical");
        Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized;

        if (direction.magnitude >= 0.1f)
        {
            float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + cam.eulerAngles.y;
            float Angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref TurnSmoothVelocity, TurnSmoothTime);
            transform.rotation = Quaternion.Euler(0f, Angle, 0f);

            Vector3 moveDir = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
            controller.Move(moveDir.normalized * speed * Time.deltaTime);
        }

        velocity.y += -gravity * Time.deltaTime;

        controller.Move(velocity * Time.deltaTime);

        if (Input.GetKeyDown("left shift") && isGrounded)
        {
            speed = sprint; 
        }
    }

}
naive pawn
#

yeah so you aren't resetting the speed...

sage wyvern
polar acorn
polar acorn
naive pawn
#

which you can't right now, because you just removed the original speed value

sage wyvern
naive pawn
#

either you need an intermediate variable that you reassign, or you need to just choose between speed and sprint without assigning

naive pawn
#

which part?

#

those are pretty basic concepts

sage wyvern
polar acorn
naive pawn
#

check for shift being pressed wherever you're applying the speed

polar acorn
#

You would have the speed value you are currently using, the sprint speed, and the normal speed. Three variables

sage wyvern
sage wyvern
polar acorn
naive pawn
#

or detect when it's released with GetKeyUp

sage wyvern
sage wyvern
dawn moth
#

how do you remove modifiers

naive pawn
#

you delete the modifier from the file...?

dawn moth
#

i dont have any option

slender nymph
#

what modifier are you trying to remove

dawn moth
#

a script

slender nymph
#

be specific

dawn moth
#

oh

#

my bad

slender nymph
#

that's called a component, not a modifier. and it very clearly has a Remove Component option

polar acorn
balmy vortex
#

hey so like how do you increase an objects transparency in unity?

echo ruin
balmy vortex
#

idk? I'm using a mesh renderer

wintry quarry
balmy vortex
#

the idea is to make it slowly fade away hence why I need it to go transparent

polar acorn
#

And then lower it

balmy vortex
grand snow
balmy vortex
#

like what's the actual code for it?

grand snow
#

Change alpha on the materials colour

#

Get color from material, update a, set color back

plain thicket
#

hi, why rotation (euler) 90 0 0 is the same with 90 90 90?

shell sorrel
plain thicket
shell sorrel
#

alot of issues like this can be avoided by working with quaternions, though just concpetally harder to understand some parts of it

slate heath
#

When I use files in unity and try in the editor, does the file persists if I press stop?

#

nvm, I just saw it does

civic forge
#

I have trouble with my c# lsp not working. From a quick look online, it seems that Unity is suppose to generate .sln files for scripts when I generate .csproj files, but it doesn't. I tried to regenerate .csproj file multiple time. Any clue what could be causing that issue?

grand snow
#

!vs

radiant voidBOT
# grand snow !vs
Visual Studio guide

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

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

grand snow
#

if using another ide then change your settings (e.g rider)

civic forge
#

I'm using nvim. I'm suppose to set inside neovim the settings to generate .snl?

grand snow
#

I dont think unity has support for vim

#

!ide

radiant voidBOT
grand snow
#

the visual studio package covers vs + vs code, and rider has its own. Otherwise no idea (zed has a community one that half works)

civic forge
#

I'm trying with vscode right now and it has the same issue.

#

Regenerated .csproj, no .snl generated, lsp doesn't work in the editor. I installed the c# and unity package.

grand snow
#

check if the visual studio package is updated in your project and you have the editor set to vs/vs code

#

if set to visual studio then a .sln is made

#

vs != vsc

slender nymph
civic forge
#

VSCode package is up to date, the External Script Editor is set to Visual Studio Code. I don't have an option for just visual studio.

grand snow
#

may be that it must be installed to even be usable...

slender nymph
#

VSCode package is up to date
by that do you mean the Visual Studio Editor package and not the Visual Studio Code Editor package? because the latter is deprecated and no longer in use by vs code

civic forge
#

Hmm i'll check

grand snow
#

yea its unified now

rich adder
civic forge
#

I can unlock a Visual Studio Editor package, but it doesn't seem to do anything. Do I have to uninstall the last one?

grand snow
#

unlock wut?

#

in the package manager in the unity registry view it should be there

#

presuming this is a recent unity version

rich adder
civic forge
rich adder
civic forge
#

But I only get the visual studio code option in the external script editor, not the visual studio.

grand snow
#

wait what platform are you on

civic forge
#

MacOs

rich adder
#

why ? Visual Studio isn't even officially supported anymore on mac

grand snow
#

windows?

#

ah well yea that explains it

civic forge
#

I use neovim, I just want to generate the .snl file

grand snow
#

(lots of these packages just "borrow" the sln gen anyway from the vs support package)

manic field
#

Hi everyone does anyone know how to add ads?

I’ve done everything about it just I want to how to right the code for it

(DM me if you want to)

grand snow
#

Use unity ads with levelplay

nova fossil
#

have a price

grand snow
#

Levelplay (was ironsource) is a mediator for other ad platforms too

dense goblet
#

what if I can't find Types in a script? am I missing a "using"?


public class SpawnManager : MonoBehaviour
{
    private float spawnRange = 9;
    public GameObject enemyPrefab;
    public int enemyCount;
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        SpawnEnemyWave(1);
    }

    void SpawnEnemyWave(int enemiesToSpawn)
    {
       for (int i = 0; i < enemiesToSpawn; i++)
        {
            Instantiate(enemyPrefab, GenerateSpawnPosition(), enemyPrefab.transform.rotation);
        }
    }
    
    // Update is called once per frame
    void Update()
    {
        enemyCount = FindObjectsByType<Enemy>(FindObjectsSortMode.None).Length;
    }

    private Vector3 GenerateSpawnPosition()
    {
    float spawnPosX = Random.Range(spawnRange, -spawnRange);
    float spawnPosZ = Random.Range(spawnRange, -spawnRange);

    Vector3 randomPos = new Vector3(spawnPosX, 0, spawnPosZ);

    return randomPos;
    }
}
dense goblet
#

its on a Prefab

dense goblet
#

its a type, heres my Enemy object

polar acorn
#

The one you're getting

rich adder
rocky canyon
#

<Enemy> means the component would incorporate a Enemy.cs script

dense goblet
rocky canyon
#

running a Find() method in the Update loop is very silly tho

#

probs be better if after u spawned in a wave u grab them all up..

rich adder
#

you should track them as they spawn, keep them in your own List

dense goblet
#

Im following the Junior Programmer guides but I gave some stuff funky names to keep track of it just in case I got confused.

#

I do wanna ask though.

``` This is looking for Objects with the EnemyAi Script?
rich adder
#

yes. technically a "Component"
if script is on a gameobject, its a Component

rocky canyon
#

gameobjects w/ the EnemyAI component ya

rocky canyon
#

but yes drag ur class EnemyAI or script from the project window onto the object.. then'd be searching for that tehcnially

dense goblet
#

Thats awesome, tysm

rocky canyon
#

thats also how we access other scripts from gameobjects that interact theGameObject.GetComponent<> or look up TryGets they're even better
like a sword hitting an enemy.. the sword could grab the Enemy script and call methods like "TakeDamage()" n whatnot
but since ur spawning in Enemy's and you know thats what ur spawning in adding them to a list would be the best way in ur case of a wave shooter.. when u instantiate one add it to the list.. and so on..

when u need ur count u can get it from ur own little list (thats pre-cached and optimized) rather than searching the scene after the fact

#

its not much to do it for 1 script.. but if u make it a habit ur game can end up crawling after it gets bigger

dense goblet
unkempt atlas
#

my player isn't able to move up or down, it floats in the air or sinks into ground or just vibrates

#

Hi, could I get some help. I've been trying to code a pokemon code 3D with 2D sprites kind of like Black and White but I get stuck at the movement

rocky canyon
#

log the Y or (whatever ur axis is for up and down) of its velocity

#

suspicions are it might be getting reset or dampened somehow

unkempt atlas
#

I'm missing something fundamental but I've going over this for 2 days

rich adder
#

also you outta show the inspectors

unkempt atlas
#

PlayerMovement script

#

Inspectors:

rich adder
#

ohh its not Kinematic..

#

rb>moveposition is usually for Kinematic movement

unkempt atlas
#

I'll send a recording of what my player does when I play

rich adder
unkempt atlas
#

yes this made some fixes I'll send it

#

still an issue

#

when the player moves forward it sinks into ground and out

rich adder
# unkempt atlas

is that the player itself going into the ground or the animation?

unkempt atlas
#

player

#

my animations (the walking animations) aren't even triggering yet

rich adder
unkempt atlas
#

how do I disable it? lol

polar acorn
#

Checkmark

unkempt atlas
#

that fixed it

#

it moves properly along the plane

#

one more thing, I have animations sprites for movement, they don't seem to be working

rich adder
rich adder
#

if you select the gameobject with animator in playmode you inspect the Animator /Controller live and see if params are hitting etc.

unkempt atlas
#

this is my animator rn

#

does it look right?

rich adder
#

tbh looks like hell

#

id probably use a blend tree lol

#

probably a 2D composite

unkempt atlas
#

bruh can I send in my proj to one of you guys and yall fix the animation

#

my brain isn't wired for this at all

rich adder
unkempt atlas
#

I'm more of a see and learn guy

rich adder
grand snow
#

some poor soul posts on reddit every day not knowing about blend trees...

rich adder
#

blend tree is goated. I use it to mix multiple "states"

#

my climb animation is just a blend tree of 2 clips alternating (left grab, right grab)
...I dont have an animator clearly.. gotta improvise lol

grand snow
#

well I guess it works but not the intended use im sure

vivid jacinth
rich adder
#

when its in the ladder trigger the movement vector switches from (Horz, 0, Vert) to (horiz, vert, 0)

#

I was gonna make a more complex system with "get on" and "get off" nodes but this is a quick proto for a jam so its not that serious

#

also use a Dot product so you only can climb looking at the ladder and not like look away and climb with your back lol

quartz jay
#

how do you fix scaling issues, when you have a position with an offset and you change the offset, it doesn't stick, how do I fix this?

quartz jay
wintry quarry
# quartz jay Yes

Mind sharing the code in question and what you expect it to do, and what is happening instead?

wintry quarry
#

"it doesn't stick" is very vague

wintry quarry
radiant voidBOT
quartz jay
#

No like can I copy and paste it here

#

with ```

#

with this

wintry quarry
#

yes, as mentioned in the thing I showed

#

if it's large though, you should use one of those services

quartz jay
#
{
    public Transform vrTarget;
    public Transform rigTarget;
    public Vector3 trackingPositionOffset;
    public Vector3 trackingRotationOffset;

    public void Map()
    {
          rigTarget.position = vrTarget.TransformPoint(trackingPositionOffset);
          rigTarget.rotation = vrTarget.rotation * Quaternion.Euler(trackingRotationOffset);  
    }
}```
strange jackal
#

I am using a third person camera view, but I find moving right or left, causes the screen to quickly move side to side, in a bad way... this yellow dot seems to indicate something about how much it is pulling to the right, is there any way - through programing to minimize this? should I slow character movement speed as I transition left and right?

wintry quarry
quartz jay
#

the rig target

#

gets the target from the IK

#

and sets it to the controllers position with an offset

wintry quarry
quartz jay
#

and when I scale an object like the arm, it's wonky

#

(the offset)

strange jackal
#

I mean I control speed in code

wintry quarry
strange jackal
#

and I use the rotation in code... I have messed with all the cimachine settings I can and they have no effect

wintry quarry
wintry quarry
strange jackal
#

ok I'll make a video and post it there

quartz jay
#

Whenever I scale the arms and fix the target offset to match the hand, it doesn't match

#

when I move the controller

#

It goes even more out of position

wintry quarry
#

how are you "fixing the target offset to match the hand"?

quartz jay
#

Ok so

#

the Target

#

goes to the controllers transform position

#

PLUS

#

the vector

#

bruh I can't type letters

#

three

#

vector three

#

see rigTarget.position = vrTarget.TransformPoint(trackingPositionOffset);

wintry quarry
#

if you don't want scale taken into account (i.e. you want an absolute world space offset) you would do it differently

#

So do you want:

  • Rotation taken into account?
  • Scale taken into account?
quartz jay
#

Wdym

#

I just don't want the scale to interfere with it

wintry quarry
#

That's what I was asking

#

then you need to do it differently. TransformPoint is wrong

quartz jay
#

oh rotation has nothing to do with this

#

that's fine

#

it's just the offset

wintry quarry
#

you want something like:

rigTarget.position = vrTarget.position + vrTarget.rotation * trackingPositionOffset;```
quartz jay
#

huh..?

wintry quarry
quartz jay
#

Why does the rotation need to be in it

wintry quarry
#

well your current code accounts for rotation too

#

so I was making it the same as your current code just without the scale

quartz jay
#

that's not what the problem is

#

it's only the position

wintry quarry
#

if you don't want scale OR rotation to matter then you just need this:

rigTarget.position = vrTarget.position + trackingPositionOffset;```
quartz jay
#

Ok, let me try!

wintry quarry
#

I understand what you're saying, but the rotation being in or out of the code matters, you need to be aware of what your code is doing

quartz jay
#

See what I'm talking about, one time it's in a good position, but when I move it, it's out of place?

#

The XYZ is the controller btw

wintry quarry