#💻┃code-beginner
1 messages · Page 733 of 1
you fire the event when the player is spawned
he can come in later
have it register itself
yeah thats true too
that's like, the whole point of using events. you use them to respond to certain things that can happen at any time.
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
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
its the great thing about this there are so many ways to solve a problem
and i somehow always choose the worst ones and make pasta out of the code
yeah when you don't know better but then you learn better, realize mistakes and learn / get exp
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
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?
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
- Make it run
- Make it right
- Make it fast
In that order.
At first made my own editor be only 1 selection at a time, then added multi select, then oops, performance issues 🤗🤗😔
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)
what takes practice is knowing when its appropriate to address certain issues early on before they become a real problem
so what did error say
did you make hit a RaycastCommand ?
What type is castPos and hit?
yea
and your IDE looks configured, it also shows in signature as you type
local variable
That's not a Type
im gonna be real real honest with you, i have barely read 1/4 of unity docs
Its more a reference than a requirement. By type they mean int, float, Vector, RaycastHit
Love that website, great references and examples on it
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
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!
Thats a loaded question, too much for this channel, try looking on UnityLearn and Youtube for resources
ok thanks
quick question, any quick functions that wait one second before the next line of code\
public IEnumerator Delay(){
yield return new WaitForSeconds(1f);
}
StartCoroutine(Delay()); where you want the pause
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
I stand corrected, but in general a coroutine with your code you want to delay within is a good way to go
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);
Ooh that I like
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.
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.
so stupid question...Are they actual physical ridges or is it an illusion caused by the grid..
it could also be brush settings
its visible both with and without the grid mode on...
thats why I showed 2 screenshots
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
whats hardness of the brush mean?
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
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
this isn't unity terrain tools this is something I wrote in c sharp thats why I'm asking
Am I able to get help here?
like if someone else has built something like this and ran into this issue
ya just ask a question, preferably in whatever channel is most appropriate for it but theres no pressure
oh i thought it terrain tool issue, could be an issue with the calculations between the tris
Unity Help, sure, just check UnityLearn for a basis, it may already have been covered
it looks fine from a fractal perlin map tho, even with extreme differences in height
Okay, so I recently bought a .blend model and the textures and rigging on it is messed up. I believe the rigging needs to be fixed on blender but the textures is a UDIM and I dont know how to bring those multiple textures onto one piece of the model
it is looking almost like a Sin wave affect in the ground, whether that helps any, hard to say without code
I bought it to upload it on VRChat if any of you's are known with that platform
honestly I have no idea what to do about that I have barely any experience with blender 😅 I think if you tried the #🔀┃art-asset-workflow channel you'd have more success with the folks in there
or #🏃┃animation
!blender !vrchat
A supportive community for Blender artists of all levels. Share your work, ask for help, and learn from others! https://discord.com/invite/blender
and theres a different one for vr chat too but im not too sure what the command for it is
I think you got the command correct the bot just only responds to 1 command per message
hello everyone!!
i need help desperately
but, not sure if it's okay to dump my whole code here?
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
ah, thanks
wait
while writing, i thought about it, and i might have the solution to my own problem
edit: nevermind, still have the problem
I've been impossibly stuck for so long on trying to get a capsule to move in 3d space XD
We are the best rubber ducks sometimes 🙃
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.
A tool for sharing your source code with the world!
BlazeBin - slwxxrrdedyq
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
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.
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
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
WeaponVars could just be its own class, if its only holding data for the Weapon : MonoBehavior
public class WeaponVars :
What do I put after the colon?
you dont need to put anything there
Ah, so just a regular class
And then I couple the Weapon Script to this WeaponVars class?
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
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
hey so like how do you get the position of another object in unity?
So I'm using the WeaponVars class specifically to check if the current weapon that's active with this component is charging up
public Transform otherObject;
Debug.Log(otherObject.position);
You assign the other object in the inspector and then it prints its position in the console
You posted code yesterday (#💻┃code-beginner message) where you get the positions of objects (both the object that has the script and another object) so how have you unlearned that in less than a day
If you want the general reference you just use
otherObject.position
Or if it's the current game object, just
transform.position
The same way you access any property, field, var, from another class
public float ClipSize => weaponSO.clipSize;
otherObject is already of type Transform you don't need .transform you're doing transform.transform.position
otherObject.position will print out the position of the assigned object
How do I horizontally stretch objects under a vertical layout group
This doesnt work
the layout group has to be controlling width too
then flexible/preferred/min sizing works
just wanted to share that as i keep learning i keep understanding that i still know nothing what the hell is a constructor 😭
public MyClass(int height)
{
playerHeight = height;
}
like i thought when i learnt about playerprefs & like inheritence OOP and like was "yeah im good now" stuff keeps popping out :(
For example this is a constructor
I think I’m getting somewhere with this
Child control width, child control height on the layer group options.
yeah i know how they look but lets say
public MyClass(Script script)
{
this.script = script;
}
why does "this" changes the script from not being a parameter
With “this”, you are referring to the script in MyClass
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
If that confuses you just name parameter _script and write “script = _script;”
ohhh so like calling the variable from MyClass and not the parameter in the constructor?
Yea
yes yes there is a Script script var
thank you im last confused now but i think i need to continue the state machine tutorial to understand more
ohhh yeah this one! i learnt html there some years ago great site
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
You mean 1?
Rough on phone
Lol yes corrected it when I saw it
It seems ok now, but my input fields are instantly crashed
0 height
You can make the input fields have a component that overrides the layout group I'd have to double check it's name
LayoutElement its called
Thank you, saved me loading up my laptop
OHHH alright understood now! now i know the "this" part
generally not needed... Avoid naming variables identically
It's a left over from an old version where it was needed
yeah the tutorial pulled that and i was like "confusing but sure go ahead"
Ok I checked everything but “Control child size - height” works now somehow
lemme actually type what the tutorial has given me so far
public EntityState(StateMachine stateMachine)
{
this.stateMachine = stateMachine;
}```
!code 🙂
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
oh yeah looks better now thanks
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
Will we need paid hosting services to make our Unity game online multiplayer?
Can we host our Unity game globally?
Most multiplayer services have a free tier that's good enough for 99%+ projects
This isnt from one class to another
This is from
Player controller --> weapon switch script --> current weapon stats
And what is switch script and weapon stats? Just another type of class, isnt it?
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
From that code it is saying that ClipSize is set as the variable data it got from weaponSO.clipsize
What are you wanting it to do
Okay so in the sniper hitscan data scriptable object is the variable you want public? If so just do data.clipSize
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
Example usage of the property being referenced:
var weapon = activeWeapon.currentWeapon;
if (weapon != null && weapon.releasedButton && weapon.isCharging)
{
SlowDown(0.3f);
}
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?
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
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
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
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
That simplifies everything lol. Thank you
Will keep that noted
(just like any asset eg. material, prefab etc.)
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)
You dont need to get any component because you already have the reference in your sniper script in your case
So what do I do?
Sniper.weaponvar.yourValues
SwitchWeapons.cs and Sniper.cs are different mono scripts
show them please
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
Which services can we use and have free tier?
Would be great, if you could use paste websites for those large blocks !code
SwitchWeapons.cs
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Didn't know it would take so much real estate, mb
This is the switch weapons script btw
Ah, so the problem now is, that you have a single class for sniper which inherits from nothing.
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! 🙏
Whichever you want 🤷 There are resources linked in #1392142304772358215 message and 
You need to create some kind of parent class that all your custom weapons inherit from, if you need single monobehaviours for every weapon because of different behaviour/animation etc. so you woul dhave a base class Weapon with a field weaponVars which you could access anytime no matter the child class
I am just wondering, where does hitscandata come from?
HitscanData seems to be a type but weaponvars is also its own type?
I have weapons
Each weapon (depending on their type, so, snipers, shotguns, rockets, etc.) have their own script
Some properties of weapons in question affect player movement directly (or at least, I want them to)
I use the swtich weapons script to swap between different weapons and I want the player controller to reference aforementioned properties that affect it
I deleted weaponvars, hitscandata is an SO
That's what I was trying to do with the WeaponVars mono script
Than you need something those weapons share like an interface or parent class you can inherit from. As an example
public class Weapon:MonoBehaviour
{
public HitScanData hitScanData;
}
public class Sniper:Weapon
{
//all your other values and methods
}
Ah, so you couple the scripts basically
You inherit
Makes sense
Yeah, yeah, that''s what I meant lol
I'll do that rn, thanks
yw 🙂
And any new weapon behavior I can just add another class?
There's a few ways you could do that, how many weapon types do you want
If you really need too. Depends on your weapons tbh.
If there are many weapons I can just make a new script so it doesn't get too convoluted I'm guessing?
You could have another category of Firearms, Swords and whatever. This really depeonds on your game design
4 weapon types but some special effects for certain ones
That inherits the primary class, obv
The more they share, the easier it gets for you to develop and expand
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}
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 😉
Why can't I modify inhereted/child classes in the inspector?
Whatcha mean? If you extended Weapon then use the correct component.
Should there be some field showing here? is it serializable?
You can't have two monobehaviours in a single script. Make two.
also, setup your visual studio correctly
yea unity gets confused and it causes problems
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
It isn't a mono, it's an inheritence
Okay 🤷♂️
(hint: it is)
It is. FOr some reason vs is buggy as hell
it inherits from a monobehaviour... making it ... a... monobehaviour
But then it doesn't modify anything in Weapon which are the properties I'm trying to reference
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.
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);
}
}
}
Can you share your code properly please ?
do you just put !code before the code
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
oh ok
Nah, I was trying to trigger the bot to give you instructions but failed miserably lmao
I get that. Please scroll up for context. I need a weapon swap script to specifically reference Weapon as a property so that my player controller can reference said property
lol
I think the new one requires the cmd to be in its own msg
you can put any class that inherits from Weapon in the Weapon slot. Everything Osteel is telling you is correct, you're just not understanding and refusing to listen
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.
Does this website work? Can you see the code? https://paste.mod.gg/cjswbvyucuyb/0
A tool for sharing your source code with the world!
so does anybody know why its giving me a notserverexception when im checking for server
its running on the host
I don't mean to sound condescending if I come off this way. Please understand that if I give a question that doesn't make particular sense it's probably because I didn't understand a part of the message without realizing it
I have a seperate mono script to handle that as I thought putting weapon swapping in the player controller was clunky
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
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.
I might be mistaken, but the way I understand your error is playerNetObj.NetworkHide()is not a legal move. It's like asking the player object to change its own visibility where the server is expected to do it.
its hiding a player object of a different player from the owner of the script
why do you think its not legal
Well, the exception itself is called "NotServerException" so I'm assuming you're trying to make on operation from an object that isn't a server ^^'
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
Ah, I'm very sorry
I see my mistake
I accidentally included Weapon in the inspector of the sniper when I should've just pu DefaultSniper, hence the confusion. Sorry for the rookie mistakes. It works perfectly now
Can I use ngrok for testing for this time?
On a side note, is it better I put the weapon switch script in the player component or a game object that holds the weapon? Obviously it makes no difference but what would be easier to work with, long term?
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.
Would that be an inheritence of the player controller that handles weapon switching?
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.
I see.
Is my proposition also a good idea, though? In retrospect, it seems natural to tell the player "hold this weapon, and slow down"
Would there be any advantage of it being an inherited class over mono?
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.
Just to clarify, "on your player" means inherited?
"on your" generally means on the game object, not code
Ah, I see
For such a setup, is this the cleanest way to do it?
yeah i greatly prefer this approach to a bunch of inheritance or massive un focused classes
I feel like having a monolithic Weapon class can get convoluted quite quickly the more weapons I add
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
why didn't sprite material change? I'm using keyframe event
I've assigned the originalmaterial, newmaterial and the spriterenderer correctly
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
Throw some debug.logs in it
ty 😄
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!
Actually, it may be creating a new material when you try to access it here. Maybe spriterender.sharedmaterial could work around that problem, but may just be better comparing against a flag instead of the material references.
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.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
framerate is also locked at 165fps (monitor refresh) so I don't think that's the issue
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.
So you basically just want this mono here to become a SO of data?
Not necessarily a SO, preferably just a [Serializable] class that I can use in any other MB/SO.
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
Yes, that's what I initially did, but it'd also require me to copy the custom inspector for that component, as well as to update the class each time Steam Audio is updated.
I hope you can see why that's not very maintainable and why I'm looking for a better solution.
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
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
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
is that an unrelated list
are you sure its an unrelated list
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
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
They're probably the same list
they are the same type but not the same list
that.. doesn't mean anything though
Where do you call Setup? What do you pass to it?
try logging oldBuildings == allBuildings, then we'll know for sure if they're really unrelated
Lists are reference types. If you pass allBuildings to this function, then both allBuildings and oldBuildings refer to the same list
oh damn, it looks like it sets it to true
So, both variables refer to the same list
Looks like it
(it doesn't set anything btw, it evaluates to/results in/yields true)
it does mean that, it just isn't "setting" anything
"sets it to true" means = true, an assignment
we currently know that they are, in fact, the same list
then work backwards - check the thing that's calling Setup, see what it's passing in
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
(what part of it didn't work before?)
like, having them be the same list isn't really an issue tbh
ok s
basiccaly
i uh
try to make game today
but i t like broke
so i need help
i tried following this tutorial:
🔴 Get bonus content by supporting Game Maker’s Toolkit - https://gamemakerstoolkit.com/support/ 🔴
Unity is an amazingly powerful game engine - but it can be hard to learn. Especially if you find tutorials hard to follow and prefer to learn by doing. If that sounds like you then this tutorial will get you acquainted with the basics - and...
but at the timestamp with the RigidBody2D thingy
it doesnt highlight cyan and just says this when i try to run the code
If your IDE is not autocompleting code or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
Finish a thought, then hit enter
Cool have fun solving this alone
please say you arent being for real
give it a read and stop spamming
11 messages for a single thought is spam
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?
i wish i knew
#1390346492019212368
also note that Netcode for Entities means you will be using the entities/DOTs workflow rather than the standard gameobjects workflow. There is Netcode for GameObjects though if you'd prefer to use the standard gameobject workflow
useless messages that add nothing to the conversation are also spam. you should really give #📖┃code-of-conduct a read
no but <@&502884371011731486> are
@bleak hull You've been made aware of server rules, follow them and don't spam.
So follow the advice then #💻┃code-beginner message
properly installed IDE will point out those errors and suggest fix.
oh crap i didnt see that
whoopsie
how do i do that? im a idiot
oh wait
i have visual studio insatlled
if only someone had linked a message that contained exact instructions on how to do so
jesus christ stop spamming. finish a thought before sending your message
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.
He is probably just young we all did that before (but i agree)
No, that's not a youth thing. That's a "being inconsiderate" thing.
dont know
just how i type
Then stop typing that way.
i dont like typing with punctuation
@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.
i have made a severe, and continuous lapse of my judgement and do not expect to be forgiven. i am simply here to apologize.
@bleak hull Consider starting with https://learn.unity.com/pathway/unity-essentials instead. It will guide you from the very beginning including how to install everything you need properly.
hmm he actually does show how to install properly IDE through the Hub as well #💻┃code-beginner message
Still, a proper course will cover much more ground.
But is netcode for game objects good for a small scale shooter where it actually matters a lot that prediction is good?
netcode for gameobjects is similar to netcode for entities, it's just the one built for the gameobjects workflow
Are there good solutions for implementing prediction for netcode for game objects?
#1390346492019212368 should be where you direct your networking related questions. it is not a beginner topic.
sooo what do i do??
the answer is still "Follow the guide" #💻┃code-beginner message
nobody said it was outdated
why would i need to update it then?
you need to configure it
follow the manual install guide to make sure you have everything configured properly
Alright
mkay
that is just one step of ensuring it is configured. if it's up to date then obviously there won't be an update for it.
ok i did tha
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.
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
A tool for sharing your source code with the world!
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
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
the object is inside a parent that already has a animator?
I'll switch to unity-talk since we're on the animator
clear the console and find out why
might be able to double click that to see where it is in your code so you can show it
it's pretty self explanatory, you cannot assign to Vector2.up. you can only use its value
in your code somewhere you have Vector2.up = someOtherTHing
=
second = shopuld be a *
Vector2.up is the same as new Vector2(0, 1) the * 10 multiplies it so it becomes (0, 10)
the underlines are pretty reliable at telling you there's a big problem
righteyo
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?
Does anyone know what might be happening?
I'm making my first project and I followed a tutorial
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
It may be difficult to see in the video, but the camera starts to jump and move suddenly
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);
}
}
Don't scale mouse input by Time.deltaTime. Learn why...
i see you watched brackey's tutorial
where he made a mistake
Oh, its delta time, thanks
Its from Dave
FIRST PERSON MOVEMENT in 10 MINUTES - Unity Tutorial
In this video I'm going to show you how to code full first person rigidbody movement. You can use this character controller as final movement for your game or build things like dashing, wallrunning or sliding on top of it.
If this tutorial has helped you in any way, I would really appreciate...
shit tutorial
i think this dave guy might be copying brackeys then 🤔
Maybe
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
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.
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?
that would be in vs code's settings, so not really unity related. but also the latter is the standard for the language
c# extention has the mode , you put it back to K&R
Eh i've put 4k hours into this project, not gonna change formatting now
Is that part of omnisharp settings?
this is obnoxious, i cant work in larger methods without things rearranging
I think its in the json yes, forgot the exact property but I'm sure you can searchh it
https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/csharp-formatting-options
I use Rider so it wont be exactly the same as VScode, but you want to look in the VSCode settings for something like this saying code style, and that will have a C# option.
No luck, attempted to add an omnisharp.json based on this solution but its still doing the same https://drlongnecker.com/blog/2018/11/vscode-omnisharp-kr-formatting/
I dont want any format features other than preserving the indent, auto wrapping parenthesis etc
This is stupid lmao
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
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
could i have a global variable somehow to store what object was last selected then?
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
I want something kind of like the sims where you select a sim, or an object, then have options or can send it somewhere
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
Sounds like an event handler (singleton) script for mouse events . . .
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
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
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)
notice how the method in the docs is different than the one you are attempting to use
0_0 i am stoopid... thanks 😄
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
Figure out which property rotates it in the inspector then find how to call it in your script
Also #🎥┃cinemachine
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
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?
"force rotation on a positive coordinate" what does that mean?
It would depend on how you're doing Ik, how your hierarchy is set up, and how your script works.
In the coordination Y
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);
}
}
The script logic is that I am looking for creating a day and night cycle originally but that also keep in mind latitude that can be used but uses two reference objects because in a plane, a reference object is needed and what I am looking for is forcing is that the object rotates in positive as long as you try again in multiple ways and I did not find anything
(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?
is there any way to avoid k___backingfield while keeping the field auto property with json nutiltiy?
Use a copy constructor or the ICloneable interface . . .
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?
Sounds to me like you wanted to have one object cover multiple depths, which I assume is not working, as objects are sorted based on their entire objects position or custom render priority.
yeah, I need it for blending transparency on a volumetric fog shader
is there a way to do it?
Shouldnt the volumetric shader already cover that?
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
does GameObject.Find find child objects?
A depth buffer is just a 2d texture. The value represents the depth of the pixel. You can't represent more than one pixels/positions in it. You'll need to render to a 3d texture or something like that.
Also this is not a beginner topic and belongs to #1390346776804069396
It doesn't care about parent-children relationship.
how come it's telling me it's destroyed then
why not? couldn't you just base the depth on the alpha transparency of an object at a pixel and add that to the existing depth buffers value?
That would just change the depth of the pixel
or render a seperate depth buffer that draws for only transparents and base the distance on the alpha for each pixel?
the latter would be an ok solution then wouldn't it
also sorry
ill do that next time
You can do that, but it will only represent the closest transparent pixel.
i dont really need anything more than one transparent object in front of another
and if i do id jsut use alpha clipping
how would i go about achieving this though?
You'll probably need a separate render pass(so it depends on the render pipeline) and render all your transparent objects into a render target.
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
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.
im using URP, but i just neverr bothered to learn how to make custom render passes & features
render graph? is that similar to shader graph?
also does that mean learning the SRP is the only way to achieve creating this custom transparency depth buffer?
No. It's mainly C# api. Though there is a debug view window that shows various info from graph.
Basically yes.
You could probably render to a render texture with replacement shaders/materials, and use that as a texture instead, but I think there's gonna be a one-several frame lag. If you're fine with that, it might be possible without extra code.
hey so like how do you check if an object/collider is touching anything?
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?
Google is a very good source, yk.
https://discussions.unity.com/t/how-do-i-check-if-an-object-is-touching-another-object/125711/2
I have literally pasted your question in google
you're right but youve taken like... the worst possible method of collission detection for your screenshot..
look into OnTriggerEnter() and OnCollissionEnter() instead
Don't look at the result of the screenshot. It's AI. I pasted a link to a source
Was just showing that googling should be your first reflex
ye thats fine, just saying @balmy vortex , definitely dont use this method
{
// do stuff
}
is this fine?
If you use 3d, yes
all physics "messages" have a 2d version
it depends what kind of collisions youre trying to detect, take a look at the difference between trigger colliders and nontrigger colliders but yes this is correct
Just in general, don't use AI also as first reflex.
if you don't know it -> google, no source or can't find it -> AI/asking others
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?
no the arg is the collider it HIT
"Collider" gives you the collision data of the gameobject you've hit
Why isn't what Unity provides, good enough?
If google doesn’t have an answer ai certainly won’t lol
all monobehaviours receive the message when a rigidbody on that same gameobject collided
all explained in the docs: https://docs.unity3d.com/6000.2/Documentation/ScriptReference/Collider.OnCollisionEnter.html
It does if you know how to work with AI
Just don't blindly copy-paste
Plus, basically everything already has been documented on google
oh but what object it hit doesn't rly matter to me in this case, can I just remove the arguement entirely?
Just means your not looking through your search engine results well enough 😄
No it needs to be there but you can just not use the argument
In that case, be smart and ask AI for sources. It searches for you.
No thanks I can search myself 😄
why are we recommending AI to people again?
does anyone know why this doesn't work? the sphere is supposed to just stop moving when it touches something but clearly I messed something up
my code for context --> https://paste.mod.gg/pcdanxlqpsut/0

was looking for something like a linked pool, couldn't find it in the docs but I got it figured out 👍
(collision other) instead of (collider other)
still literally just doesn't work
Yeah I'm pretty sure it's cause the fireball doesn't have a rigidbody component, which it needs to detect collisions
no rb, and you probably don't need 2 sphere colliders
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
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
define properly
the Shoot() function doesn't always shoot at the player
put some logs in there , figure out what gets actually called vs animator showing
can we import old swf assets in unity? (am trying to remake a game from 2011 lol)
no
arrrr!
will have to convert then oof
even converting stuff it will not all be 1 for 1, since flash could do vector graphics stuff unity is not capable of
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
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
I found a free flash decompiler. if I convert assets to some frame based animation of pngs will that work?
when you hit a object with a racyast you hit its collider then you can use GetComponent to get a other component on that object
can I convert them in .gaf?
no clue what that is, i have not touched flash stuff since the early 00's
I was thinking to build my childhood game for old times sake. oof
could rebuild it without needing to rip anything from antique fileformats
huh, i built a whole as messaging system between objs and i could of just done this...
just remake the assets in your own style
everything works, there are no errors, the problem is probably with the logic of the code but I can't find it
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
the problem is that he hits the player 15% of the time
am beginner idk ;-;
its the standard way to do it, also lets you fetch components via interface types or sub types as well to have a more generic way to do things
we all were at some point.
would be impossible to extract the logic anyways
its basically a pokemon type game
since even if you could get the as2/3 code out non of it would be translatable in any meaningful way
so I have to comeup with logics myself
you're supposed to log your variables to make sure everything has the values its supposed to have
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
all the variables are assigned and correct
the problem is with this wait
if your bot keeps missing surely the aim direction variables cant be right?
or there is a factor they are not considering
yea so the problem is with the logic of the code
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
is firepoint right? I don't see where you set that
the playerBox is the transform of the collider the bot has to hit
in the variables upside
yea the variables are all correct
you could also draw a debug ray to make sure the raycast is going in the right direction
already did
is it hitting something else first such as the object that is emitting the cast
and it's going in the right direction
ah it could be hitting the bots own hitbox
like the gun?
or another collider
anything, just log of its hitting and if it is see what its hitting
k I'll do that
you sound like you dont want to fix i)
he seems to be trying
anyway I gave my suggestion (debugger)
best way to detect silly mistakes and inspect what happens
also firePoint, is that like your gun or something?
it says it's hitting the ground
but sometimes it hits the player
there must be ground in the way
I want, I'm on it since a long time
0.6f is a pretty big radius
Start with logs, then move onto a debugger if you still cannot figure out whats happening
yes
I've already logged almost everything, everything works, the only problem is it's hitting the ground
and I'm actually building my game in devlopment build as u suggested me
with script debugging options enabled
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
you think it's the problem?
why are you asking me
its your game, test things
figure out if thats the issue, or like debug draw spheres along the path or something
You can use a debugger in editor or a dev build
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
never trust the ai
yea, it's so ass for unity
it is for everything
it's fine for generating filler text tbh
ray to small haha
but finding help isn't always easy
genai is the opposite of finding help
but yeah ray too small makes zero sense
think about your game and what you want to accomplish not waht AI is telling you
k bro ty for your help
there are many reasons to use ray, or reasons to use sphere cast it depends on what you are trying to accomplish
that's what I always do, but I use ai to try to learn things or understand things I don't, I don't trust it
but also think about things like how tall is a bot in your game and how tall is a player
you should stop with those too tbh
it's just a word randomizer trying to be convincing, rather than correct
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
lol
If you have to go fact check everything it tells you to do then why bother with the first step and instead just go learn it from the places you fact check with
how do you learn to do things u dont know then? if there are no yt tutorials
ask on discord or search around the web
By breaking it down into smaller things that you can figure out how to do, and combining them
youtube is not the only resource. docs, forums, etc exist
breaking it down into smaller problems, docs and experiments
docs, web search, experimentation, etc
and also yeah, you generally don't look for full tutorials
you learn and understand simpler concepts and then combine them
okayyy
I just downloaded reddit, I hope it'll help me
I've heard it's a productive forum
you did what
uhhh well i mean that's not wrong, but it's also not super friendly at times, so be aware of that lol
generally reading existing forum posts is sufficient
well it wont hurt to ask surely
it just wastes your own time if it's already been asked
forums have search bars for a reason
u just like search on the web?
yeah
okay
google searches generally bring up Reddit posts if there's something relevant on there already
do be aware that searching is also a skill in itself
also break your problme down
don't search some broad huge thing, break it into the steps needed to do that
sometimes you gotta cast an incantation -site:reddit.com after:2018 before:2022
okayy thanks guys
I've just changed it to 0.05
it now hits "FPSPlayer" gameobject that's the parent of the hitbox
anyway I'll figure out how to do it dw
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.
first off, configure your ide
!ide
If your IDE is not autocompleting code or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
VS Code
ok, click the link that says vscode
secondly, where are you resetting the speed? (and format it properly please 👇)
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class 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;
}
}
}
yeah so you aren't resetting the speed...
how do i reset it?
What is supposed to be putting the speed back to what it was
The same way you changed it, but you put in the value you want
which you can't right now, because you just removed the original speed value
then how do i make it that only if shift is pressed that the character will sprint
either you need an intermediate variable that you reassign, or you need to just choose between speed and sprint without assigning
and how do i do that?
how do i choose between speed or sprint without assigning
You would assign it, you just need to keep the original value somewhere too
check for shift being pressed wherever you're applying the speed
You would have the speed value you are currently using, the sprint speed, and the normal speed. Three variables
i'm quite a beginner so i don't know how
but is there a way to say if shift isn't pressed?
Yes. Check if it's pressed, and then do something when it isn't
or detect when it's released with GetKeyUp
alr txh
thx
how do you remove modifiers
you delete the modifier from the file...?
i dont have any option
what modifier are you trying to remove
a script
be specific
that's called a component, not a modifier. and it very clearly has a Remove Component option
yeah i just saw thank youi
hey so like how do you increase an objects transparency in unity?
Are you using a sprite renderer component?
idk? I'm using a mesh renderer
you would need to use a transparent material
well I kinda need the material to start off fully visible cuz I'm using it for a projectile
the idea is to make it slowly fade away hence why I need it to go transparent
Then you would use a transparent material but with full opacity
And then lower it

This may cause issues if left as transparent but with opacity as 1.
It can be a pain to change between opaque and transparent on a material at runtime but it's possible.
how do you change an objects opacity btw?
like what's the actual code for it?
Change alpha on the materials colour
Get color from material, update a, set color back
hi, why rotation (euler) 90 0 0 is the same with 90 90 90?
Gimbal lock is the loss of one degree of freedom in a multi-dimensional mechanism at certain alignments of the axes. In a three-dimensional three-gimbal mechanism, gimbal lock occurs when the axes of two of the gimbals are driven into a parallel configuration, "locking" the system into rotation in a degenerate two-dimensional space.
The term can...
thank you
alot of issues like this can be avoided by working with quaternions, though just concpetally harder to understand some parts of it
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
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?
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
follow the instructions linked above
if using another ide then change your settings (e.g rider)
I'm using nvim. I'm suppose to set inside neovim the settings to generate .snl?
If your IDE is not autocompleting code or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
the visual studio package covers vs + vs code, and rider has its own. Otherwise no idea (zed has a community one that half works)
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.
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
for vs code check this page, it has steps to take if the typical configuration steps didn't work https://unity.huh.how/ide-configuration/visual-studio-code
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.
may be that it must be installed to even be usable...
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
Hmm i'll check
yea its unified now
is probably with the logic of the code but I can't find it
I mean... literally why I said to put logs and find out where it breaks / goes wrong..
I can unlock a Visual Studio Editor package, but it doesn't seem to do anything. Do I have to uninstall the last one?
unlock wut?
in the package manager in the unity registry view it should be there
presuming this is a recent unity version
probably because its installed as dependency of Engineering package afaik
Yeah it says that in the package
as long as the version is 2.0.22+ you're good
But I only get the visual studio code option in the external script editor, not the visual studio.
wait what platform are you on
MacOs
why ? Visual Studio isn't even officially supported anymore on mac
I use neovim, I just want to generate the .snl file
(lots of these packages just "borrow" the sln gen anyway from the vs support package)
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)
Use unity ads with levelplay
have a price
Levelplay (was ironsource) is a mediator for other ad platforms too
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;
}
}
What can't it find
sorry, <Enemy> in the enemyCount = FindObjectsByType<Enemy>(FindObjectsSortMode.None).Length; }
its on a Prefab
What is Enemy?
its a type, heres my Enemy object
No, the script
The one you're getting
just reminder.. tags are not the same as components
<Enemy> means the component would incorporate a Enemy.cs script
wait, that might be it, one second
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..
you should track them as they spawn, keep them in your own List
Yeag Im pretty sure that is what Im looking for, tysm
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?
yes. technically a "Component"
if script is on a gameobject, its a Component
gameobjects w/ the EnemyAI component ya
but yes drag ur class EnemyAI or script from the project window onto the object.. then'd be searching for that tehcnially
Thats awesome, tysm
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
tysm for helping me, it means a lot.
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
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
yeah I've done that
I'm missing something fundamental but I've going over this for 2 days
Send the code pls
also you outta show the inspectors
have you tried turning off interpolation
ohh its not Kinematic..
rb>moveposition is usually for Kinematic movement
try putting Kinematic on, does it do the same thing?
yes this made some fixes I'll send it
still an issue
when the player moves forward it sinks into ground and out
is that the player itself going into the ground or the animation?
are you sure? cause it looks like it animated. try disabling the animator
how do I disable it? lol
Checkmark
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
so it was animator animating the transform or just visuals
in what way they aren't working ? You should check the conditions / paramas you set and see whats happening
if you select the gameobject with animator in playmode you inspect the Animator /Controller live and see if params are hitting etc.
tbh looks like hell
id probably use a blend tree lol
probably a 2D composite
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
why did you pick gamedev then lol
I'm more of a see and learn guy
lol..so "see" the link I sent and redo the animation system properly with using blend tree, will make the workflow 100x easier..
some poor soul posts on reddit every day not knowing about blend trees...
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
well I guess it works but not the intended use im sure
How did you make this sytem ? Do you use a Trigger collider to change the statut of the character ?
pretty much
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
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?
Is this a code question?
Yes
Mind sharing the code in question and what you expect it to do, and what is happening instead?
Is it ok to post it all here
"it doesn't stick" is very vague
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
yes, as mentioned in the thing I showed
if it's large though, you should use one of those services
{
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);
}
}```
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?
ok so what is this supposed to be doing and in what way is it differing from your expectations?
Ok so
the rig target
gets the target from the IK
and sets it to the controllers position with an offset
Is this a code question, or perhaps a #🎥┃cinemachine question?
not sure
I mean I control speed in code
well yes, TransformPoint takes scaling into account
and I use the rotation in code... I have messed with all the cimachine settings I can and they have no effect
I think it's hard to understand what you're talking about here without a video for example
but it sounds like a #🎥┃cinemachine question
Are you saying you want the offset to not take scaling into account?
ok I'll make a video and post it there
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
how are you "fixing the target offset to match the hand"?
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);
yes but this takes into account the rotation and scale of vrTarget
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?
That's what I was asking
then you need to do it differently. TransformPoint is wrong
you want something like:
rigTarget.position = vrTarget.position + vrTarget.rotation * trackingPositionOffset;```
huh..?
we need to know whether rotation of the vrTarget matters to write the correct code though
Why does the rotation need to be in it
well your current code accounts for rotation too
so I was making it the same as your current code just without the scale
if you don't want scale OR rotation to matter then you just need this:
rigTarget.position = vrTarget.position + trackingPositionOffset;```
Ok, let me try!
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
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
First off can you make sure your tool handle position is set to Pivot mode?