#archived-code-general
1 messages · Page 293 of 1
ive been trying to think of the right way to do these things, and i finally did it 😄
Bump on this question
Another example from another game,
My current results
Vector3 handsDirection = hand2.position - hand1.position;
transform.rotation = Quaternion.LookRotation(handsDirection );```
See how it flips around after going above 90 degrees?
I know jack about quaternions so I dont know how to work with this
how to you apply changes from Input to Finite State Machine. Do you have to check whether a state can perform some capabilities before executing it. Like when player is swimming, they can't jump
A "state machine" is just a function of code that allows for other paths during certain states.
A state machine can be a bunch of if statements that take your input and allow certain actions during certain states.
i.e. in the standing state, a player can press C to crouch or shift to run. A crouching state would allow for C to uncrouch, but not run
New input or old input?
It could change the way you approach this
if(CharacterState == State.Standing) {
if(Input.PressedC) { CharacterState = State.Crouching; }
if(Input.HoldingShift) { CharacterState = State.Running; }
}
else if(CharacterState == State.Crouching) {
if(Input.PressedC) { CharacterState = State.Standing; }
}
else if(CharacterState == State.Proning) {
if(Input.PressedC) { CharacterState = State.Crouching; }
}```
@lunar python An example of a state machine that uses input to handle a character's pose
what if I want the player to do both jumping and moving at the same time?
I assume that first if should set state to crouching?
Oh yes my bad
platformer usually allow player to do a bit of air hovering while at the peak of jump
Well you could do something like this
if(CharacterState == State.Standing) {
if(Input.PressedC) { CharacterState = State.Crouching; }
if(Input.HoldingShift) { CharacterState = State.Running; }
if(Input.PressedSpace) { Jump(); }
}
else if(CharacterState == State.Crouching) {
if(Input.PressedC) { CharacterState = State.Standing; }
}
else if(CharacterState == State.Proning) {
if(Input.PressedC) { CharacterState = State.Crouching; }
}```
Jumping isn't exactly a state, and can be separate
But this way, you could only jump when standing
What does this accomplish?
Gives player the ability to do certain actions, cool
I seperate states by Unique conditions that allows player to do certain actions
Trying to add doors to my dungeon generator but for some reason the script I made is doing literally nothing. ```cs
public class DoorSpawner : MonoBehaviour
{
[SerializeField] private GameObject doorPrefab;
private void OnTriggerEnter(Collider other)
{
// Check if the colliding object is another DoorPoint
if (other.CompareTag("Door"))
{
// Destroy the colliding DoorPoint and its associated doorFiller objects
Destroy(other.gameObject);
Destroy(other.transform.parent.gameObject);
// Instantiate a new Door prefab at the position of this DoorPoint
InstantiateDoor();
}
}
private void InstantiateDoor()
{
// Instantiate the Door prefab at the position and rotation of this DoorPoint
GameObject door = Instantiate(doorPrefab, transform.position, transform.rotation);
}
}``` I'm trying to make it such that when two doorpoints are colliding (Meaning that two rooms with doors at that spot are adjacent), they will each be destroyed along with the wall filler and replaced with a door. At the moment nothing happens when they collide and I am not sure why
Attached a couple pictures showing how the doorPoint is setup, and what one and the filler look like in the scene
In the hierarchy doorPoints are children of the fillers
do you have the requirements to make OnTriggerEnter to work
what exactly are the requirements
You're missing one component there for it
Wait what am I missing
otherwise, you can just do like a overlapbox operation
figured rigid body was for physics and stuff
part of me thinks I should've chosen an easier first project but part of me is really having fun with the complexity
collider is part of physics too, but yeah I don't know why the trigger method has to be so connected to it
something like this is fine tho?
alright nice, sort of works
just gotta make it only instantiate one door somehow
and also fix the prefabs that have the doorpoint slightly too low
I realized a flaw with my scriptable object game effects which are "when X happens do Y". I wanted to make a feature, every few seconds heal some amount. Since im using SO, i realized there is only one instance so every character with this effect will add to the counter. Then one character ends up consuming the health and the timer resets.
I need unique instances and know I can Instantiate(SO) or CreateInstance but is there a reason to use one or the other? I assume Instantiate is the same but it copies the data from my existing SO which I want.
Also are there any downsides to use Instantiate here? It seems to work so far but I am just curious if there is something else I need to do. Like do I have to destroy the objects after?
Instantiate usually copies anything serialized usually (much like prefabs) while CreateInstance is like making a new SO instance in the editor as it'll always have defaults
defaults from the original SO instance
dont quote me on this ;)
I did actually make a effect system using SOs only but I ditched that idea for just plain ol' c# classes
I'm kinda struggling on this end. Any advice?
Issue is that both doorpoints register the collision and go through their process, which involves spawning the door
so two get spawned
i might just create some poco based on the effect if i notice any errors
public class DoorSpawner : MonoBehaviour
{
public bool QueuedForDestruction = false;
private void OnTriggerEnter(Collider other)
{
if(QueuedForDestruction) return;
if(other.TryGetComponent(out DoorSpawner door))
{
Destroy(door.gameObject);
door.QueuedForDestructon = true;
}
}
}```
try something like that
or some similar idea
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DoorSpawner : MonoBehaviour
{
[SerializeField] private GameObject doorPrefab;
private bool doorBeingSpawned = false;
private void OnTriggerEnter(Collider other)
{
// Check if a door is not already being spawned and the colliding object is another DoorPoint
if (!doorBeingSpawned && other.CompareTag("Door"))
{
// Set the flag to indicate that a door is being spawned
doorBeingSpawned = true;
// Destroy the colliding DoorPoint and its associated doorFiller objects
Destroy(other.gameObject);
Destroy(transform.parent.gameObject);
// Instantiate a new Door prefab at the position and rotation of this DoorPoint
InstantiateDoor();
}
}
private void InstantiateDoor()
{
// Instantiate the Door prefab at the position and rotation of this DoorPoint
GameObject door = Instantiate(doorPrefab, transform.position, transform.rotation);
// Reset the flag to allow for the next door to spawn
doorBeingSpawned = false;
}
}``` this is what I currently have but spawns two doors anyways
so it's not the door checking OnTrigger but this DoorSpawner?
there's no race conditions that I'm aware of
All rooms have doorfillers and those fillers have doorpoints as children. If two overlap, that means a door should go there, so all of those should be destroyed and a single door spawned
I have a dumb idea for a solution
have each generate a random number when they collide and the lower number gets destroyed
rock paper scissors for life
im not too sure, but something to run step by step in the debugger if needed
Ugh I've been trying to use a coroutine or invoke to add a delay in order to spawn one door but the coroutine return makes the following line unreachable, and the invoke just doesn't work and idk why. ```cs
private void OnTriggerEnter(Collider other)
{
if (!doorBeingSpawned && other.CompareTag("Door"))
{
doorBeingSpawned = true;
Destroy(other.gameObject);
Destroy(transform.parent.gameObject);
Debug.Log("Invoking InstantiateDoor");
Invoke("InstantiateDoor", 0.1f);
}
}
private void InstantiateDoor()
{
Debug.Log("Instantiating door...");
// Instantiate the Door prefab at the position and rotation of this DoorPoint
GameObject door = Instantiate(doorPrefab, transform.position, transform.rotation);
// Reset the flag to allow for the next door to spawn
doorBeingSpawned = false;
}```
In this code the first debug prints but the secont debug never does
Tried with coroutines earlier but those didn't work either and idk why
you destroy the whole parent ?
thats one of the steps that has to happen yeah
can't invoke if its destroying
should I change the order
Just tested with the parent destruction happening second to last but still doesnt work
wdym second to last?
You cant run a coroutine on a Monobehaviour that is gonna get destroyed next frame and expect it to wait for 0.1s or what ever
before the flag set to true
Idk how to do this im ngl I've tried like 30 different things in the last hour
This script is attached to every door spawn point, if theres no delay two doors spawn at every spot
there doesnt need to be delay
I think we need a hit more context on your set up, code and what you want to achieve
there's no race conditions
that means something is triggering twice when it shouldnt?
delay might be hiding a bigger issue
I provided a couple screenshots above
Every doorpoint has the script attached to it, and they each check for a collision
so when a collision happens rn it leads to double trigger
you can check gameobject IDs and only run function on one script
for the most part, Unity is single threaded (as far as user-space callbacks go) , if it happens on a single frame then it's probably executing in some order
oh that's a pretty good idea
Sounds like a better alternative to my rock paper scissors idea thank you lmao
And it worked
tyvm
Hello i just have a question about unity netcode im trying to add a force to an object with a severrpc as the client has no rights. but it just isnt the player is being referenced properly and the m value is correct and changing with the rest of my code if anyone has any tips please help. btw the function is being called in update.
public void movementServerRpc(Vector2 m,ServerRpcParams serverRpcParams = default){
var clientId = serverRpcParams.Receive.SenderClientId;
if (NetworkManager.ConnectedClients.ContainsKey(clientId)){
var client = NetworkManager.ConnectedClients[clientId];
client.PlayerObject.GetComponent<Rigidbody2D>().AddForce(m,ForceMode2D.Force);
}
}
extra info:
i have got a network trasform on the object and it is not updating the postion in the sever
its not just the add force trying to change the trasform also does nothing although it is being called as the debug.log is working
hey guys, so I want to directly download from OneDrive using this method:
https://api.onedrive.com/v1.0/shares/u!XXXXX/root/content
where XXXXX is the base 64 equivalent of the url
however when I convert the url to Base64URL format and try to open the final url, it responds with:
{"error":{"code":"unauthenticated","message":"The caller is not authenticated."}}
Any idea how to fix this?
Presumably you are not authenticating with OAuth2 and are not providing the correct token in the request
how can I do that?
isn't there some simpler way of downloading directly from onedrive? or maybe use different storage?
ok an update on the problem it is infact increaceing the veloctiy but not changeing the position which i didnt think was possible
Did you try impulse mode instead of force?
i dont really know why this would change anything as adding the force is not the problem it is that fact that when it is added it doesnt change the position
I had the same problem and just changing it to ForceMode2D.Impulse fixed it for me, perhaps are you sure there isn't any code that is manipulating with the object's position?
#archived-networking but you probably shouldnt be doing multiplayer if you arent really confident in coding/debugging. what you are doing in the server rpc doesnt really make sense, this script can just have direct access to the rb. The same way it does in single player. Then you can just add force in like fixedupdate based on a network variable (for the vector2)
If a person does not own the object, it will not move the object no matter what you assign to the velocity.
There is code that is doing it. The entire networking framework
i im relatively confident with unity and debugging but i am trying to learn networking i thought i would use a sever rpc to add the velocity as when i use a network transform it is quite delayed if you think it is a ownership problem it would be great if you could help me understand it better in #archived-networking
I dont really do networking anymore, you should just post it there regardless
thats all good thats for the tips anyway
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class InteractionManager : MonoBehaviour
{
public Text valueText;
int progress = 0;
public Slider slider;
void OnEnable()
{
PlayerInteractor.OnInteract += HandleInteractEvent;
}
void OnDisable()
{
PlayerInteractor.OnInteract -= HandleInteractEvent;
}
void HandleInteractEvent()
{
UpdateProgress();
}
public void UpdateProgress()
{
progress++;
slider.value = progress;
StartCoroutine(ResetSliderAfterDelay(2f));
}
private IEnumerator ResetSliderAfterDelay(float delay)
{
yield return new WaitForSeconds(delay);
// Reset progress and slider value after the delay
progress = 0;
slider.value = 0;
}
}
I am trying to make a slider that interacts with my interaction system and it works but I can´t get it to reset the slider
Do not cross post
sorry but noone was helping
not the point
that's the script of my camera, but if I use collision.gameObject.CompareTag("change1") it will detect camera's collisons, how to get the collisions of my Player?
because like this it doesn't work
You can only get the collision occurring to this object. Your way of writing it the other way is just nonsense
yeah I noticed that getting just the y position would be enough, now it works, I'm so dumb
like this
{
if (Input.GetMouseButtonDown(1))
{
Vector2 MousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector3 direction = MousePosition - (Vector2)transform.position;
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
Quaternion rotation = Quaternion.AngleAxis(angle, Vector3.forward);
_rigidbody.MoveRotation(Quaternion.RotateTowards(transform.rotation, rotation, _rotationSpeed * Time.deltaTime));
}
}
I may be stupid. but for some reason this is not working. it gives me this error.
Player.RotateTowardsCursor () (at Assets/Scripts/Player/PlayerMovement.cs:58)
Player.FixedUpdate () (at Assets/Scripts/Player/PlayerMovement.cs:29)
the line with an NRE contains the variable that is the problem
Why is everyone using public variables for ScriptableObjects? Like this looks like a big sin for me.
in this case, line 58
it is 🙃
I checked and nothing is there
line 58 is: Vector2 MousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
then add a breakpoint, look at debugger, and see what the contents of your variables are
it was working before and now it is not so idk
yeah the { get; } getter is not working and the only option seems to be setting up manual getters?
they should all be [field: SerializedField] public int myVariable {get; private set;}
it needs a private setter to actually define the backing field and connect to unity
okay thanks
hey guys. there's a lack of collider primitives in unity. is there a good asset with primitive colliders? what would you recommend?
3D collider primitives are provided by PhysX.
so you aren't going to be adding your own primitives
what knid of primitives are you looking for?
make em in blender then use a Mesh collider
what if i want to change cylinder collider's shape size and offset like im able to do with default colliders in unity?
cant
yep. thats why i asked if you guys know the best pack for it. i searched and there are several. im trying to get a primitive collider pack where you have flexibility with size and shape
make new ones, one of the best optimizations you can make in Unity is to use models which have not been modified
so my custom blender colliders will be more optimized than default ones in unity?
ok then
mesh colliders are expensive, tread carefully. The basic ones unity has are always more performant
Primitive colliders are shapes that are easy for PhysX to reason about.
I imagine they were chosen for a reason.
Toruses, notably, are not convex.
Cylinders are harder to reason about than capsules.
I seem to be getting a lot of perf hog on Physics2D.FindNewContacts any idea what might be causing this?
AHAAAAAAAAAAAAAAAAAAAAAAAAAA
I'VE FIGURED OUT THE BUG
when the linerenderer is turned off, it counts as the renderer turning off, triggering "OnBecameInvisible" and starting the countdown for the offscreen kill
so I just need to tell it to reset the offscreen-ness when the linerenderer goes away
Hey. I would like to hide the objects between camera and player. How is it called and how could I do this best? I tried with ray cast but that only works semi good
depends what effect you want, there are shaders for this or you can do it manually with a few raycast/ capsulecast
it will proably be easier with some sort of cutout shader though
I tried it with a shader. But with that the walls are cutout strangely
idk what strangely means
one moment
well
for some reason now it works as expected
XD
before in play mode it was messed up
i saw like two cutout cirlces
an inner and outer and between them the wall was there
could be it needed playmode to work properly
it was in play mode XD
oh so you only need 1 ?
No I had two materials with diffrent cutout size. so it somehow messed it up in render
ahh gotcha
but anyway. thanks for resonding 🙂
Hey, I've noticed some weird behaviour with AudioSource.isPlaying. Basically, I'm using it to play random sounds from a set one after another. It will play the first sound, then check isPlaying until it can play the next ones. But it never gets to the next one.
Even if the source is totally silent
Any ideas?
isPlaying going to false or wat
Alright, this is my current code:
private void Awake()
{
_rigidbody = GetComponent<Rigidbody2D>();
}
private void FixedUpdate()
{
SetPlayerVelocity();
RotateInDirectionOfInput();
RotateTowardsCursor();
}
private void SetPlayerVelocity()
{
_smoothedMovementInput = Vector2.SmoothDamp(
_smoothedMovementInput,
_movementInput,
ref _movementInputSmoothVelocity,
_time);
_rigidbody.velocity = _smoothedMovementInput * _speed;
}
private void RotateInDirectionOfInput()
{
if (_movementInput != Vector2.zero)
{
Quaternion targetRotation = Quaternion.LookRotation(transform.forward, _smoothedMovementInput);
Quaternion rotation = Quaternion.RotateTowards (transform.rotation, targetRotation, _rotationSpeed * Time.deltaTime);
_rigidbody.MoveRotation(rotation);
}
}
private void RotateTowardsCursor()
{
if (Input.GetMouseButton(1))
{
Vector2 screenPosition = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
Vector3 worldPosition = Camera.main.ScreenToWorldPoint(screenPosition);
Vector2 playerPosition = new Vector2(transform.position.x, transform.position.y);
Vector2 direction = ((Vector2) worldPosition - playerPosition).normalized;
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
Quaternion rotationmouse = Quaternion.AngleAxis(angle - 90, Vector3.forward);
_rigidbody.MoveRotation(Quaternion.RotateTowards(transform.rotation, rotationmouse, _rotationSpeed * Time.deltaTime));
}
}
private void OnMove(InputValue inputValue)
{
_movementInput = inputValue.Get<Vector2>();
}
}
Whenever my character touches another object (especially a corner of an object) it starts randomly spinning
lock rigidbody rotation on Z
that locks all my rotation haha as my code rotates the rigidbody
nvm
if your character is a circle anyways than you don't really need to rotate it with physics
if you do want to use physics, you could just override the rigidbody angular rotation at all times
how would i make it so it rotates without physics?
could've sworne MoveRotation would still work with locked Z
lock the rotation like what was recommended earlier, then just manually rotate the rigidbody
and maybe try this, I am unsure if it works as well
nah they have that already thats why i was confused
oh, I didn't read the code up there
got it
set rotation moves when its locked
move rotation doesnt
but the problem is
that removes my dampening
yea ig because MoveRotation still uses physics
doesn't seem like it should remove your dampening.. or at least I wouldn't expect it to. should be same rotation getting calculated, just applied differently
how would one fix it?
well, explain what you mean by dampening exactly
if you mean the rotation is instant now for some reason, maybe you accidentally got rid of your RotateTowards.. ?
nope
it is instant
but i did not remove
the rotatetowards
i think its because rotatetowards uses physics (maybe?)
private void Awake()
{
_rigidbody = GetComponent<Rigidbody2D>();
}
private void FixedUpdate()
{
SetPlayerVelocity();
RotateInDirectionOfInput();
RotateTowardsCursor();
}
private void SetPlayerVelocity()
{
_smoothedMovementInput = Vector2.SmoothDamp(
_smoothedMovementInput,
_movementInput,
ref _movementInputSmoothVelocity,
_time);
_rigidbody.velocity = _smoothedMovementInput * _speed;
}
private void RotateInDirectionOfInput()
{
if (_movementInput != Vector2.zero)
{
Quaternion targetRotation = Quaternion.LookRotation(transform.forward, _smoothedMovementInput);
Quaternion rotation = Quaternion.RotateTowards (transform.rotation, targetRotation, _rotationSpeed * Time.deltaTime);
_rigidbody.SetRotation(rotation);
}
}
private void RotateTowardsCursor()
{
if (Input.GetMouseButton(1))
{
Vector2 screenPosition = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
Vector3 worldPosition = Camera.main.ScreenToWorldPoint(screenPosition);
Vector2 playerPosition = new Vector2(transform.position.x, transform.position.y);
Vector2 direction = ((Vector2) worldPosition - playerPosition).normalized;
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
Quaternion rotationmouse = Quaternion.AngleAxis(angle - 90, Vector3.forward);
_rigidbody.SetRotation(Quaternion.RotateTowards(transform.rotation, rotationmouse, _rotationSpeed * Time.deltaTime));
}
}
private void OnMove(InputValue inputValue)
{
_movementInput = inputValue.Get<Vector2>();
}
}
what if you just do transform.rotation = rotation for them instead, and also double check your rotation speed (although I doubt thats the issue)
well yeah.. your camera is a child of your player (it will inherit rotations)
how was it not doing that behavior before?
tbh idk, my camera doesnt get affected by my player's rigidbody rotation or position
that is very weird considering in this video from earlier I can see the player rotation changing in the transform https://cdn.discordapp.com/attachments/763495187787677697/1221490801721475214/2024-03-24_17-04-35.mp4?ex=6612c4f5&is=66004ff5&hm=5abae5a3a56c77076b5d6c15a77d0fdd44d7b656bf83f95454d985dc27326690&
i know
also this fucks it up as now if i hold right click (which changes the rotation to where my mouse is) while moving it bugs out
which it wasnt doing with the physics
probably mostly luck that it was working before, your logic is incomplete. You should only rotate towards one or the other (either movement direction or mouse direction)
right now it tries to rotate towards both when you hold the mouse button
no
alright
I am saying that it was just luck that it appeared to look good, it was still actually trying to rotate to 2 different directions at the same time
the delay of the interpolation physics must have made it unnoticeable
you should wrap your "RotateInDirectionOfInput" code in a if (!Input.GetMouseButton(1))
yeah thats what i was about to do
ty
I actually don't know how but now the dampening works with
_rigidbody.SetRotation(rotation); so 🤷♂️
thank you anyways <3
glad it works
do any one know how to solve this bullet issue
void FireBullet()
{
foreach (var point in ShootPoints)
{
Debug.Log(playerRigidbody.velocity);
var bullet = Instantiate(bullets, point.transform.position, point.transform.rotation);
bullet.AddForce(playerRigidbody.velocity + (point.transform.forward * bulletSpeed), ForceMode.Impulse);
}
}
doesn't seem the pivots are correctly placed?
by pivots u mean firepoints?
and bullet
nah they are placed correctly when i am not moving it works perfectly fine but when i move things get messy
thats local pivot or center ?
local pivot
you tried also without playerRigidbody.velocity in addforce ?
yeah same thing
do you have a trail or somerhing?
it looks like the bullet is shooting fine is just the trail lagging
yeah trail is child of bullet
yeah I think thats whats causing that "look" but the bullet is shooting fine
try speed up duration time you will seee it will prob be better
the trails last too long, yes
they're weirdly rotating
i think that is because the car is rotatating and they always go forwards so its an illusion i guess
when i need to debug something fast i have mapped keys for Time.timeScale = 0.05f or something
looks like it starts lagging behind yea
you try increase the bullet speed?
yea i already doubled it
you're passing the rotation of now not the one you're going to be in. by the time it happens the car already rotated , I think..
never tried shooting rigidbodies on moving objects like this, i typically go for raycasts on that. So I'm not sure
with raycast cant show that a turret is shooting
sure you can
but i have to move the bullet manually and it will also lag i guess
like from starting point to the end point
you can simulate it faster than a physics object can accelerate in physics loop
or to just add muzzle flash and hit effect to fake it?
like the lines right?
yeah lines
didn't understand what u meant here
you can make instant ones too or give them a slight delay , but never tried on rotating object that adds extra challange
for example you could lerp the trail renderer between start + end (a point on ray)
ideally cause Update will run more frequent should be able to move it faster than a rigidbody can accelerate (accounting for mass ig)
hmm will try with raycast which ever feels better will use it
worth a shot
ForceMode.Impulse is taking mass into account another thing to consider
is it only me whos not seeing a problem with the bullets
bullet is spawning behind the firepoint
also you're def passing the wrong rotation or the pivot you showed me was in global mode @merry sierra
physics... a double edge sword
yeah that i was trying something now i put bullet firepoint bit more forward
it looks much better and with muzzle flash it will look better
have you tried putting it in late update
yeah its in late update only
why is that?
so that the movement will take place first and then it will get update position to spawn
it looks as if the bullet is coming out a bit slow like the prefab of lazer has its origin set at center and when it is instantiated, half the lazer is behind the muzzle
And when the object is instantiated, its next fixedupdate would be called in the next cycle right?
private void FixedUpdate()
{
if(!isReloading)
{
timer += Time.deltaTime;
if(timer > firerate)
{
timer = 0;
currentMagazine -= 1;
FireBullet();
if(currentMagazine <= 0)
{
isReloading = true;
reloadtimer = 0;
}
}
}
else
{
reloadtimer += Time.deltaTime;
if(reloadtimer > reloadingTime)
{
reloadtimer = 0;
timer = 0;
currentMagazine = maxMagazine;
isReloading = false;
}
}
}
I put this loop in fixed update

why is time.delta in fixedupdate
it's fine
Time.deltaTime is set to be Time.fixedDeltaTime whilst FixedUpdate is running
what there is that feature?
small suggestion: instead of doing timer = 0, do timer -= firerate
Imagine the fire rate is set so that you fire 49 times per second
you fire on physics update 0
at physics update 1, you're almost ready to fire again, but not quite
at phyiscs update 2, you fire, and you reset the timer to 0
so you only fire 25 times per second
will implement that
If you rate of fire can be greater than 50, also consider using a while loop until timer < firerate
that way you can fire many times in one step
thanks for the help guys
if you instantiate an object on frame 0, then apply force to it on frame 1, would it takes until frame 2 for physics to take place?
🤔
oh you also apply force on frame 0 so that would make it frame 1?
Physics doesn't happen on frames at all.
Physics updates happen 50 times per second by default.
well..it does happen during a frame; it's just that you can have zero, one, or many physics updates happening in a single frame
Looks like physics happens before the normal update loop
So if you apply a force on frame 0, and Unity decides to run a physics update on frame 1, the force will be used at that point.
well im talking about physics frame of course
I'd like to have a billboard world screen UI facing the camera, however my current issue is that there are multiple cameras (split-screen game), is it possible to make the world screen space Canvas UI with split-screen, if so .. How? If not, what other way would you suggest to show a text above the player which should be the amount of people taken out?
he instantiate object in fixedupdate, which kinda sounds like this thread https://www.reddit.com/r/Unity3D/comments/dfk1h2/object_a_gets_instantiated_in_fixedupdate_but_the/
put two versions of script, one only seen by cam1 and one only cam2.
Hmm, good idea. Although would that not hurt the performance having multiple canvases for each player?
is it multiplayer?
So if I had 4 players, I'd have to spawn 4*4 canvases
couch co-op
how much player could it possibly
you already have two cameras thats already pretty performance heavy
you're only rendering 1 on each cam, not both
give it a try
4 players max
fair
you can really just do one big canvas that you have multiple smaller regions in
multiple canvases will also work. either way, you need to make sure each player's UI is properly sized.
i would recommend multiple canvas though. cuz if something change in a canvas, the whole thing gets redrawn
I already have a canvas for each players view and assigning camera layers per player
Yeah. I actually need to go profile this...
I use one huge canvas for my main menu
My game already has a performance hit with 2 players running on a 1070 laptop
I do deactivate almost all of the individual menus, though
So I'm kind of worried about whether the performance will go down the drain
The game is a 3D co-op "bomberman" like game
I have already implemented object pooling so at least thats no issue for now.
make the game, use profiler to catch anything
the first optimization tip is seriously split canvases
don't not make something simply for premature optimizing
Done
my game dont even have canvases yet cuz everytime I add a canvas, the pixels gets jaggy
and distorted
Each player has its own canvas.
I think most of the performance issues comes from unoptimized models thanks to MagicaVoxel.
around 4.7M verts in total, and the bombs generate around 500K verts (each).
wtf
There are a lot of particles
where did you even grab those bombs, it could bomb your pc you know?
that is kinda horrible, is the environment at least set to static ?
i remember the 2 million vertices toothbrush in a yandere game
The bomb model itself is just a sphere model with a flat shader
the particles are the issue
Invisible bomb 🧠
Hey! I am looking for a fairly standard way to manage variables. Ammo, health, Death state, items collected.
Do I careate a game Manager state and store all the player specific variables in this file and then load and save using this class or do people just shove variables into random classes as they develop and just accept that things might get messy 😅
you put the variables on the objects where it makes sense to have them. for example you wouldn't have both a Player Health and Enemy Health variable on the same object as that would generally not make any sense
we do daily code renovations, so just do what you think is suitable
sure, this makes sense. The variables I am focusing on mainly is persistant data for the player .
Ammo, health, lives, points, XP
Inventory items
you generally want to have input in seperate files from your player data, just create a player controller for handling external influence, a data manager for each entity, and a input controller
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
you dont want players to be able to directly modify their stats in online games just through their local code
you can have a single object that is used purely to save/load that data. but most of it wouldn't be on the same component unless you're writing some terrible god class that does everything
I get that. Reason for me asking is, I find that I have randon variables everywhere that the player needs . Stupid example : I have a isDead boolean sitting on a gameState Manager class. I have player health script on a UI component that gets updated via an Event and I have an inventory system set up on a INventoryManager . Now I need to write these data sets to a file to save and load and I find myself looking everywhere trying to keep track of everything. I am 100% going to miss stuff upon saving and loading this way
Ya, so no god class! Promis XD
Hihi I have a question
A video explaining it or a general explanation would be great
So in games, for example stardew valley: after/during a certain triggered event a building in the map changes/upgrades
Whats the simplest way to do this?
https://hastebin.com/share/galabuviti.csharp
I need some help instantiating the GameObject inside the chunk length float please
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
The easies way is to have the trigger or event be called at the end of an animation or sequence . In this case a video will play and toward the end have code call the new 'sprite/3D gameObject' to replace the current one
What does that mean?
BTW Start is capitalized incorrectly
health script on an UI element?
sounds like recipe for disaster
Yup!
I was nooblet when I wrote some of the code. so I am trying to fix my stuff
Okok thank you!
I had assumed it would be similar to that but I wanted to ask since im not the most experienced code wise
I assume you are an artist getting their hand at game dev right
I just threw that in, in the actual code it's correct
I'm trying to instantiate the trainStat1 prefab in a certain length. It is currently instantiating on any empty game objects with the tag "trainStat1", that works but it does it in other places I don't want it to. So how do I limit the length it instantiates?
Me? If so, Yeah I am 
Ive dabbled in visual novels quite a bit but I wanted to try my hand at something more hands on
you could start from learning MouseToWorldPosition to get position of mouse, Raycast to get the gameobject you are pointing at, learn some basic UI stuff to make buttons pop up after click, add functions to buttons and change sprite to desired ones
I think thats what you are looking for
visual novels?
like the click ones that you get from scenes to scenes
Yeah smth like that
Im a studio arts major alongside a creative writing major so it was a pretty naturally coming gateway into game design
well thats a good start, I guess you already knows most of the basics
I have no idea what is means to "instantiate in a certain length"
upgrading building doesn't make much difference from updating conversations in visual novel though so idk what you need help with
Im instantiating an object, and i want to make it spawn inside of a certain length
objects wont be instantiated here | | | objects will be instantiated here | | |objects wont be instantiated here
I was mostly asking about the general concept as I wasnt sure what route was/would be the most efficient 
i dont quite get what you are meaning
like pattern for instantiating?
public GameObject[] trainStat1;
public float chunkLength = 90;
void Start ()
{
GameObject[] trainStat1EMPTY = GameObject.FindGameObjectsWithTag("trainStat1");
foreach (GameObject position in trainStat1EMPTY)
{
int randomIndex = Random.Range(0, trainStat1.Length);
GameObject randomPrefab = trainStat1[randomIndex];
Instantiate(randomPrefab, position.transform);
}
}
In this code, I am Instantiating prefabs into any empty object with the tag trainStat1
that works
but I have separate chunks, so it then spawns into that one and the others too
I need it to only instantiate inside of the chunk length
Is it better to make base classes or static classes for cross script communication?
read the docs about the Instantiate function, im quite sure you are getting it wrong on the second parameters
you really arent understanding me are you
yeah, no nothing helpful there
I need it to only instantiate prefabs inside of the chunk length
the just check if the position.transform.position is inside of chunklength
and how would i do that?
even if i checked that and then let it instintiate it would still instantiate outside of the chunk into others
Anyone made a distortion 2d mask before or has any idea how I could? Trying to make a distortion/glitch effect that can either fully or partially distort/glitch objects or areas in my viewport?
then check if the bounds of the object in a position overflows into others
so how would i do that?
depends on the object shape
holy Arceus! 😄
2d or 3d?
3D
OP bomb 👏 it can explode verts counts too 🙌
Okay, removed all particles. Now it doesn't even go above 10K 
god, making my own custom implementation of pathfinding using multithreading is such a pain in Unity. (pathfinding must be custom, that's for my thesis)
i'm proud that it's finally working as intended and can handle up to 192 bots queueing path at almost the same time
oncollision enter also counts if a collider in a child object hits something right?
if the script is on the same gameobject as the Rigidbody, yes
Need some help with mouse aiming in my top down game. It 'almost' works, but there's some bug where it consistently fire off target by a few degrees.
Shooting towards bottom of screen or left of the screen, the bullets feel only very slightly anti-clockwise from my cursor.
Shooting towards the top of screen or right of screen, the bullets are a lot more anti-clockwise from my cursor.
This is my aiming code where I just turn the play to face in direction of where my mouse cursor is.
Plane playerPlane = new Plane(Vector3.up, transform.position);
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
float hitDist = 0.0f;
if (playerPlane.Raycast(ray, out hitDist))
{
Vector3 targetPoint = ray.GetPoint(hitDist);
Quaternion targetRotation = Quaternion.LookRotation(targetPoint - transform.position);
targetRotation.x = 0;
targetRotation.z = 0;
this.transform.rotation = Quaternion.Slerp(this.transform.rotation, targetRotation, rotateSpeed * Time.deltaTime);
}
And this is code for where I actually shoot out bullets from my gun -
GameObject projectileInstance = Instantiate(projectile, bulletSpawnPoint.transform.position, Quaternion.identity);
projectileInstance.transform.rotation = StaticUtilities.GetCrewLeader().gameObject.transform.rotation;
Quaternion pelletRotation = Quaternion.AngleAxis(UnityEngine.Random.Range(-spreadFactor, spreadFactor), Vector3.up) * projectileInstance.transform.rotation;
projectileInstance.transform.rotation = pelletRotation;
Why are you doing cs targetRotation.x = 0; targetRotation.z = 0;
You shoulkd never be touching parts of a quaternion like that
delete that
surprised that even works
Because I want the rotation only around Y axis. It's top down game, the X and Z rotations for player don't matter
Oh this is also wrong
nah you have that covered already with the plane raycast
but this is wrong:
if (playerPlane.Raycast(ray, out hitDist))
{
Vector3 targetPoint = ray.GetPoint(hitDist);
Quaternion targetRotation = Quaternion.LookRotation(targetPoint - transform.position);```
oh wait nvm that's ok
just delete that weird quaternion code that is definitely wrong and broken
x and z on a quaternion aren't what you think
I'll be very honest, Quaternions and angles confuse the heck out of me. A lot of this is copy pasted and modified from other examples on the internet. Maybe some chatGPT mods
Ok and I'll be honest, delete these lines, they're very wrong
See if that improves anything
wouldnt you specify that the z is the up axis though if this is 2D
for look rotation
I assume 3d top down
ah ok
with gameplay on the x/z plane
Hello everyone, not sure if this is the right channel for this but I got a question. I want to make a camera look at and render ONLY a UI canvas, how do i do that?
Just use a Screen Space - Camera canvas
And use a culling mask to make the camera only render that UI
No, didn't help. No difference - good or bad
What would help with troubleshooting? One thing is the weapon is not centered exactly on the player. Does it need to be?
well yes that's a problem. That means of course this caculation would be off
perhaps you should be aiming the gun at the cursor
The bullet does rotate in same direction as player though. So weapon being at a wrong angle should not matter?
projectileInstance.transform.rotation = StaticUtilities.GetCrewLeader().gameObject.transform.rotation;
how do i stop these balls from appearing around my game object??
This is not a programming question. Disable the gizmos for light probes
Okay sorry and thank you
yes same direction as the player but since it's offset to the side, it will miss the target
Yeah, I see that now. My weapon was at a slightly different angle than the player. And the Ray calculation from center of player to cursor. So a lot of slightly whacked calculations
First, I am going to make weapon and player angle the same way.
Second, in my calculations, I am going to measure from where bullet spawns to the cursor, keeping it all consistent.
Let's see how that works out.
Hey. I’m curious as to how people here like to approach their inventory systems they design for games. Not looking for a YouTube tutorial as I’ve followed them before.
Just want to hear people’s thoughts on how they approach this (not detailed code but high-level descriptions, ie using scriptable objects for xyz, dictionaries for this, etc)
Hey sorry if this sounds dumb but I'm new to this so looking for some help. Basically I have a texture that I need to check every single pixel for it's green value then add it to a float. Since my texture is 1440x1440 pixels it has to do that ~1.9 million times which is way to much. So my idea was to scale down the texture to 100x100 pixel. It will still keep the original texture but just be a worse quality. I did something looking around but I can't find anyway to do this. Would what be the correct approach to achieve this? Thanks!
basically:
- ScriptableObjects for the "base" data for items, i.e. its name, the UI sprite for it, the effects it has, the max stack size, etc.
- a serializable, runtime Item class for runtime instances which has a reference to the base data SO, may contain runtime data like durability, use count, etc.
- As for the inventory itself it depends how you want it to work but it could be anything from a Dictionary<Item, int> to a List<Stack> where Stack is a struct with an item reference and a quantity.
Thanks!
Sorry for the code screenshot, but I didn't know how else to show the values during the debug process. As you can see in the variables watcher to the left, leftOffset is 0 but for some reason when I assign it to attached (a RectTransform), it sets it to NaN and it disappears in the scene. Anybody know why this is happening?
Looks like this is the value
leftOffset is NaN
not 0
Well yeah, but I don't see why that would happen. All the variables that calculate leftOffset are 0, and I'm not dividing by 0 anywhere.
One sec
x Nan
y -
you'd have to show how it's calculated
float leftOffset = positionOffset.x - (sizeOffset.x * anchor.x);```
According to VS code positionOffset.x is 0, sizeOffset.x is 0, and anchor.x is 0.
one or more of these things is NaN to result in NaN here.
Is VS Code being a little silly and changing NaN to 0 when I hover over a variable?
doubtful
guh
make sure it's NaN at the moment you're debugging
the code could be running multiple times
and not be nan every time
I'll check
I don't know if this is a valid way to do it, I debug.log Time.time and then collapsed the output to see any repeats and I got no repeats. Does that mean it's only running once per frame? Is there a better way to check?
time and delta time are updated once per frame. What exactly are you trying to do?
I was just checking if a certain piece of code was running more than once per frame, I didn't know how else to do it.
Maybe check/print the frame number?
It's good to check the API docs from time to time. There's a lot of useful stuff you can discover.
https://docs.unity3d.com/ScriptReference/Time.html
Ok yeah no repeats.
I have absolutely no idea why this is happening. A value is 0, I'm appplying it to a rectTransform then it turns into NaN
It could be that some other values are invalid causing a NAN internally. Like the anchors.
I see. If that's the case I'm just going to do a band-aid patch I don't think I want to debug something happening behind the scenes.
That was just a guess. I don't k ow the whole context.
It looks like you had a NAN in the debugger, so it's probably your code and not something internal.
Share the whole script. Maybe there's something obvious.
Sure one moment I’m moving around at an airport
Negative values probably problematic too beyond zero division but I wouldnt think it turn nan
https://issuetracker.unity3d.com/issues/nan-values-in-rect-transform-when-the-anchor-is-set-to-stretch-and-all-the-rect-transform-fields-are-set-to-0
this could be related
Reproduction steps: 1. Open the attached project "ReproProj" 2. Open the “/Assets/Scenes/Game.unity” Scene 3. Expand the “Canvas” Ga...
It's not entirely clear what exactly is being NAN I'm that screenshot. Is attached a rect transform?
Yes
And the pop-up window is of what variable?
OffetMin
My plane is leaving soon so if you see any red flags reply to my message and I’ll get back to it when I land
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
How do I set up my sprites / tilemaps in unity so the thing that gets shown in front is by the pivot that has a lower Y.
it's in project settings somewhere
global transparent sorting axis
isn't that just for the Y position? not the pivot
oh, the pivot you need to do it independently for each sprite in the sprite editor
and then on the sprite renderer you sort by pivot
oh ok i got it thanks
I'd reset the values in the script to those of the rect transform or some safe values the first time it's attached. You're likely calling SetRectValues while some of the fields are initialized with default values which could be invalid. For example, anchors having size of 0 could be the source of the issue.
What Simex linked could be related:
#archived-code-general message
hihi I just have one more quick question
ok so im trying to find information on a general concept I want to add to my game but nothings coming up when I look it up so im confused if maybe my english is failing me or if its just not something easy to do?
I want to add favorability bars to my game (if that term rings no bells think like how stardew valley has the heart system or how bg3 has the trust bar)
but I cant seem to find any videos or threads on it?
I dont think its a rare concept so im wondering if im just calling it the wrong thing maybe?
it's just a bar like health that updates based on a stat (value). there isn't anything different or special about it. you track and update it the same way, similar to the approval rating for dragon age . . .
you won't find a specific tutorial about it since it's just a stat value—shown visually with a bar—used for a custom system in certain games . . .
That actually makes so much sense why didnt I think of that lmao 
thank you btw!
(also Approval rating is a way better term than what ive been saying it makes a lot more sense to)
i have a simple class for a reactive value for this sort of thing
it's like a morality system. some characters will have a morale stat . . .
ReactiveValue<T>, which holds a private field of type T, and public setter. If the public setter tries to set an actually different value, it invokes a public event action, to notify anything that needs to know that the value has changed.
yeah I know, my english was just failing me a bit and "favorability bar" was somehow the best I could slot in for my mind to work lol
yeah, i noticed i kept making a property/field setup with events over and over. much easier to make a reactive/observable class and struct to use instead . . .
i got the idea from Fen or Burrito, I think
burrito is especially big on reactivity systems
affection is another name, if it is romantic. like harvest moon
approval is more political
yeah I was gonna add both (trust and romance one), but had to sort out what I was actually doing first and it didnt click in my mind that you can just set it up basically like (using Random's example) a HP bar
a lot of games don’t use a bar/number, and hide the fine details. Usually you only get an indication at specific thresholds
more information => min max affection.
less information => more relaxed/vague
Oh hey, glad to see more people are adopting reactivity systems 😄
yeah thats true, I just really like how bg3 did it and they used a visible kinda slider-esc bar
i said his name 3 times, and he popped out of the mirror
KEKW
pretend this server has that emote

I got you lol
anyways huge thanks to both you and random, im off now to do the gruelling work that is
✨ designing a city ✨
i just need to refactor it into some old stuff (if i feel like it) and my core package which i use for all my projects . . .
it is not worth refactoring, but it is worth making it, and adding it in to anything new
it’s just cleaner, and less spaghetti
i don't do 🍝 , though, i'll eat it, like i am right now . . .
fyi, my vanilla reactive value also has a field for default value, to call ResetToDefault
default being defined in constructor
every variable I want to be a reactive value winds up wanting this behaviour
that makes sense . . .
When I use a vertical scrollrect with elastic - there's some amount of "buffer" that I can drag past the top of the content. Empirical testing shows it's some.. magic number, about 500 pixels? Is there a way to set/get it programmatically so I don't just have to guess and hope that it works for all sizes?
(I'm currently putting a background on the content rect that's top/bottom -600/-600 but I'd prefer to exact-size it)
seems like something I'd just toss in double its value and call it a day
maybe ive done that before actually
Hey guys. I’m working on an interesting project simulating cars precisely. So, I have a function that runs and matches up the rotation of the wheels to the speed of the car and vice versa (I’ll take slip into consideration later), but my problem is that when cars steer, the car rotates a little bit as you turn. But in Unity, since I’m custom programming the rotation and movement of the car, I also have to code the rotation of the car. What’s the best way to go about the steering?
Rotating the chassis is the greatest problem
yeah, probably gonna be fine.. double will be too much though since the actual content is typically like 5000px
do you have the front tires rotating and the back moving cares in real life
but i use these everywhere in my app and the .. lack of a data point to specify the "above-scroller" is kind of annoying
Wdym?
so basic the back wheels push the car and the front wheels rotate the car
In essence tho my configuration rn is awd
Well I guess 4wd is more accueste
So what will happen is my wheels will rotate. Now there is ackermann steering which is based off of a point and then ig there is other steering
So if I were to rotate the wheels I could theoretically figure out which way the car should go but figuring out how much it rotates is different
basiclly unity's physics will calculate most of it
How
the wheels will use the rigidbody
I already have the wheels setup that isn’t the problem
It’s how the chassis rotates
And how the back wheels follow the rotation
i'm not sure maybe you should look up a youtube video
Have
Shouldn't it be rotated in the direction of the movement?
public class WallHit : MonoBehaviour
{
private void OnTriggerEnter(Collider other)
{
if(other.gameObject.tag == "Bullet")
{
Destroy(other.gameObject);
}
}
}
i am using this script to destroy my bullet but for some reason its not happening any idea
How would I use OnDrawGizmos to draw a circle for a collisionPt?
if you're debugging points of collision you can always instantiate a gameobject and throw a script onto that that constantly draws the sphere at the location
you put on trigger enter on the box, but you did not set the box's box collider to be trigger, make the bullet a non trigger and the box a trigger and it should fix it
tldr swap triggers
What do you exactly mean by throw a
Script on an instantiated game object? Sorry, bit of a novice
I understand how to instantiate a new game object in code, but how would i add a script to it programmatically?
Instantiate(GizmoPrefab, col.gameObject.position, Quaternion.Identity)
I see
make a prefab that contains a script for the gizmo
Ahh duh haha.
you may want to add its own timer to expire though
yeah, the gizmo prefab script can hold all that and destroy itself
also, probably parent them to something so they don't spam the scene :)
I fixed that, however, I am experiencing a problem with my radar where the icon appears within 90 degrees of the ray. Here is my code: cs private void CreateAndMove(Collider collider) { Vector3 colliderPosition = collider.transform.position; Vector3 desiredPosition = colliderPosition - new Vector3(player.transform.position.x, 0, player.transform.position.z); Vector3 position = this.gameObject.transform.TransformPoint(desiredPosition / (scannerRange * transform.localScale.x)); var angle = Vector3.Angle((colliderPosition - player.transform.position).normalized, Vector3.forward); if (Mathf.Abs(angle - ray.transform.rotation.eulerAngles.x) <= 1f) { StartCoroutine(PingDuration()); if (pingVisible) { Instantiate(badGuy, position, transform.rotation, transform); } } Debug.Log("Angle: " + angle); } void RotateRay() { ray.transform.Rotate(0, rotateSpeed * Time.deltaTime, 0); }
Is there a version of Vector3.angle that is always a value between 0 and 360?
(I know its been like 14 days, I'm sorry.)
what do you get if you change var angle = Vector3.Angle((colliderPosition - player.transform.position).normalized, Vector3.forward);
to
var angle = Vector3.eulerAngles((colliderPosition - player.transform.position).normalized, Vector3.forward);
?
eulerAngles isnt a Vector3 func...
looks to me like the docs begs to differ. but I also just woke up so I might be confused about it :p
you are creating and destroying a brand new Texture2D every single time you call this
just reuse the Texture2D object
i omitted some code that sets the value of the read pixel to the the value of a referenced material
Yeah, thats not a thing.
https://docs.unity3d.com/ScriptReference/Transform-eulerAngles.html if youre talking about this, you have to create the var yourself
yeah if you want help optimizing your implementation, then don't omit code when sharing it
i editied it so that its the original now
okay and how often do you start this coroutine
I am trying to make a system where if the Energy is online, the energy online container object should be active else it should say that energy is offline
The interactable object implements two interfaces
{
StartCoroutine(PickColorCoroutine());
}```
great, so every single frame that the button is down. #archived-code-general message
yes, i was mentioning when you said to just reuse the same texture#archived-code-general message
none of what you have said would prevent you from reusing a Texture2D that you create instead of creating and destroying one every frame. you create a ton of garbage by doing that
additionally, have you read: https://docs.unity3d.com/ScriptReference/Texture2D.ReadPixels.html
ReadPixels is usually slow, because the method waits for the GPU to complete all previous work first. To copy a texture more quickly, use...
private IEnumerator PickColorCoroutine()
{
// Wait until all rendering is complete
yield return new WaitForEndOfFrame();
if (tempTexture == null)
{
tempTexture = new Texture2D(1, 1, TextureFormat.RGBA32, false);
}
// Calculate the correct position to read from based on the mouse position
Vector2 mousePosition = Input.mousePosition;
Rect readPixelRect = new Rect(mousePosition.x, Screen.height - mousePosition.y, 1, 1);
// Read the pixel from the RenderTexture
tempTexture.ReadPixels(readPixelRect, 0, 0);
tempTexture.Apply();
// Retrieve the color from the texture
Color pickedColor = tempTexture.GetPixel(0, 0);
// Set the brush color
brush.Color = pickedColor;
foreach (Renderer visualizer in colorVisualizers)
{
if (visualizer != null)
{
visualizer.material.color = pickedColor;
}
}
}
i couldve sworn i implemented this before i went with my current solution (i did) and my frames still tank by the same amount
thanks i'll take a look
how do I stop this from happening? (this referring to the light overlapping the object and going through it.)
my object has a collider.
now i would try a shadow cast but it doesn't work great either (as you can see in second pic), like i want the light to follow the red lines and not light up the object like that
Thats not how lights work
well
In no dimensions do shadows look like what you want them to
i know
im not trying to make it a light
im trying to make it a field of view marker
Its still right
not really. if you stand behind a door way you will see a somewhat straight line
it doesnt expand unless you are really close to it
The second screenshot is accurate to how the line of sight would work in real life. If you want something different you'll have to code it yourself
hey guys?
anyone can say me what i need todo, that i can fold in and out the Headers in inspector?
Configure your !ide first
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
lol? that is configured xD i just use the dark mode xD
Common Unity types are not correctly highlighted so your editor is not configured to use Unity
if i turn the dark mode then the highlighted colors are normal xD but that broke my eyes xD
so pls dont try to find any problems where i dont need/have help/problem
It's not about finding irrelevant problems, you're expected to have a configured editor if you want to receive help. It also benefits you as the user a lot to have everything set up correctly.
Please just answer my question and stop worrying about any crap
Have a look at Naughty Attributes, they have a Foldout attribute
is that an asset in unity store?
why is your naming conventions so inconsitant
Because his editor is not correctly configured to suggest correct naming /s
nah, he just uses dark mode Kappa
FYI if they are using VS Code and using a theme that does not support semantic highlighting or turned off semantic highlighting altogether, then it falls back to simple TexMate grammar based syntax highlighting and will not highlight Unity types differently because it won't have syntax information. Not saying that's definitely the case here, just saying it doesn't always mean IDE is not configured.
Interesting, I never seen that happen but that sounds reasonable behavior from VSCode
In VS Code you can even turn off all highlighting so it's just black and white, but still have full language server diagnostics and error reporting. It's extremely configurable.
Hi all! What would be the best and safest way to insert something into a MySql database running on a server from a standalone Unity Application?
Sounds awful lol
It annoys me when you can't tell value types from reference types, let alone not even differentiating types from members
have a backend website that interacts with both Unity and MySQL
do you have any sources for getting started with that? I'm not that familliar with web-development
what OS is your database running on?
thank you
Yeah realistically no one sane would do that and just use semantic highlighting like a normal person. But having TexMate grammar highlighting is what allows VS Code to give (not very good but better than nothing) syntax highlighting for practically every popular language and file format in the world without having a language server for every single one of them.
Ok, then probably Node.js is best for you. it has easy access to both http and MySQL
https://nodejs.org/en
https://www.w3schools.com/nodejs/nodejs_mysql.asp
https://www.w3schools.com/nodejs/nodejs_http.asp
It also allows me to open a 1 million LoC C# file (artifacts, not actually source code) in less than a second and have good enough syntax highlighting to work with, rather than having to wait for language server to slowly process the entire file. VS could never do that.
You could set up a .NET API running behind Apache, then you can continue working with C#. Remember anybody can reach your web application so some form of security should be added.
.NET has solid support for MySQL and also things like PostgreSQL and SQLite. There's a general framework that's "usually" used called Entity Framework which provides a code-first solution to database communication and it makes it super easy to work with.
i see - thank you both!
i have two web requests in unity, one of them gets back an image url from the internet the other one downloads it and turns it to a texture, my problem is the second one doesn't wait for the first to fetch
What makes you think that?
i run the code, it gets to the second part and it gives me n error says it cant fetch url or whatever because it's empty and then after a while the url is generated
wdym 'the url is generated' ?
okay let me explain this further, i'm using amazon s3 bucket to store users profile picture, my bucket is private which means i can't fetch images directly from there, so for that i wrote an api in nodejs, to access the image and create me a temporary url for that image, in unity first i run that api to fetch the url and then i need to download it to display the image as a raw image texture,
sreenshot the console so I can see the Debugs
i call the first part which is getting the image url, then i call gettexture to download the url and display it as texture, but if you look at the console log it ran the second part then the url got fetched
this does not seem to be in any way related to the code you posted
yes i changed it abit, i seperated the first part and second and put them in two IEnumerator, but still nothing changes, same result
why the pixel perfect is showign up like this ?
you've made it worse, the second coroutine will run before the first has completed.
Also how do you expect us to help you if you do not provide correct code
This new code is much worse than the original code which would have worked properly
these are the options for the pixel perfect
@knotty sun @leaden ice okay here is the orginal code and it's still the same.
not quite the same, you took out the most important information. The Debug.Log of URL passed back
is this chat gpt code
yes
Hey, Im using URP and I have a Camera which is disabled and I render its view to RenderTexture using camera.Render().
The problem is it renders Gizmos as well. How can I prevent it?
how do i save my game so then i can covert it into zip and sumbit it into the dropbox
For what purpose?
Which Dropbox?
Ok but are you turning in the project or the built game
This is honestly a question for your teacher
both
@leaden ice
Then make a build and put the build folder and the project folder into a zip archive together, what's the issue
i tried that but when i open the build file its blank ;-;
as i open it says made with unity then a blank template ;-;
i did..
@leaden ice what if i wanna share my file
so the teacher can look throught the file
not the game like whole stuff
What's SampleScene? Isn't that an empty scene?
IDK..
😄
it is default empty scene probably
If you don't know why did you include it in the build?
so when you compile, the game starts in that scene and nothing happens
Zip it
I WANNA SHARE THE FILE
That's the build
None of this is code related BTW
You tell me friend
It's your project and your computer
Where'd you put it?
You should talk to your teacher not us.
ok
Yes
Then do it
But that’s too general
You can’t rotate the car in the direction until the car moced
And at that point you are going in increments so I would need to calculate the amount it needs to rotate and then do it per frame
But simultaneously get the direction in which the wheels need to move as well as make the back wheels follow
For some reason I'm facing this issue. Where I update variables in my code it doesn't reflect on the unity hub. The DeadZone here is -30 but it is reflecting -20 on the UI.
No idea why this is happening.
Serialized values override initialization values in code
public float florp = 100;
This declares a field named florp with a field initializer that sets it to 100.
Field initializers are applied during the creation of the object.
Unity applies serialized values after the object is created.
"serialized" meaning "saved", basically
anything that shows up in the inspector (if you aren't doing any Wacky Custom Editors, at least) is a serialized value
The field initializer will only matter when creating new instances of the component, or when you right click the component and hit "Reset"
Sorry new to game dev didn't get it.
Does that mean the value that's in the Unity hub?
Fen explained it in detail. Values in the Unity editor override those default values in code.
suppose I create a component called "Example"
using UnityEngine;
public class Example : MonoBehaviour
{
public float myField = 123;
}
When I attach the "Example" component to a game object, Unity stores some data.
you can actually just drag a scene or prefab aset into a text editor to look at it
MonoBehaviour:
// a bunch of other junk
m_Script: {fileID: 11500000, guid: 816d62879a223453490b2d4b131c57d0, type: 3}
myField: 123
Unity records that "myField" contains a value of 123
If I then edit the value in the inspector, the serialized data changes.
so if I change "myField" to 100, it remembers the value.
MonoBehaviour:
// a bunch of other junk
m_Script: {fileID: 11500000, guid: 816d62879a223453490b2d4b131c57d0, type: 3}
myField: 100
That's what it means to be "serialized": the data is stored.
If I made that "myField" private, then:
- myField would not appear in the scene or prefab data at all
- Unity would not remember a value for myField
- myField would not show up in the inspector
Unity has to turn this scene or prefab data into actual objects.
It does this by:
- Creating the object
- Assigning all of the serialized values into it
In step 1, Unity creates an Example object. At this moment, myField has a value of 123.
In step 2, Unity looks at the saved data and restores all of the saved values. myField is now 100.
So, it basically stores the value that I assign first time (which is called serialization)?
So, if I do public float myField = 123; I will have to reset every time?
If you don't want Unity to remember a value for each instance of your component, you should tell it to not serialize the field at all.
By default, private fields aren't serialized.
You can use also use the [System.NonSerialized] attribute.
Yes, but private won't be present in the inspector. Right?
So, change it from code every time.
A non-serialized field won't show up in the inspector, yes.
since unity doesn't save it, there'd be no point in displaying it in the inspector: you couldn't do anything to it
Yes, that'll be the 'ideal' behavior for me. I'm not sure if everyone thinks the same but say in other coding that I do changing the variable reflects and overrides the values present. There also we have 'inspect' but as soon as we change something in the code (and save) it reflects soon overriding anything that we did in the inspect.
I'm not sure if thinking in that terms is good.
this sounds more like what you'd expect from a debugger
yes, that's not the right way to approach the inspector
The inspector is used to configure components.
You create scenes and prefabs that contain GameObjects. GameObjects have Components attached to them.
Components have serialized fields that you assign values and references to.
Okay, but say I did some stuff on the inspector like changing the value and now I found the ideal settings. Now I wanna 'save' that. Say the code is present on github. Saving won't happen right? Since the code still has value 10 while in the inspector say I changed the value to 15.
version control isn't relevant here at all
If you want to change the default value the field will have when you create new instances of the component, then change the field initializer
This won't affect any existing instances.
so if you decide you want myField to default to 15, change it to public float myField = 15;
Any new instances of your component will start out with a value of 15.
This is confusing kind of lol
Serialized values of existing instances (scene objects, prefabs, etc) will be stored in .scene/.prefab/.meta files, which will be pushed to your source control.
well, no, they just live in the actual scene and prefab assets
The field initializer provides the default value. You'll get that default value if nothing replaces it.
That's all.
Okay, so if someone else decides to run my game locally. (Again, new to game dev so I might be throwing general dev concepts that don't apply) Then they'll see 15 on the unity hub and 10 on the code. Is that it?
"run my game locally"?
i don't know what you mean.
Say pull my code and test it.
Do you mean if they check out your project from source control and open the editor?
They'll see exactly what you see.
Yes, ''
The serialized values are part of the scene or prefab. Scenes and prefabs are assets. Assets are put into source control.
All of that stuff should be replicated through version control. Only personal editor preferences and caching files may be left out.
Okay, so 15 on the inspector and 10 on the code?
Yes. They'll see exactly what you see in your own editor.
Okay, that makes sense.
Unity would be completely unusable if you couldn't make changes to scenes and prefabs (:
Yeah, I am just trying to relate it with core dev stuff that I do at work. Here, from my understanding so far, the inspector matters a lot compared to dev. So, you dw reset it after you change a variable in the code I'm assuming.
If you want to discard the serialized data for that specific instance of the component, then yes, you'd reset it.
So, if I want to apply the values that are in the code. I'll have to press reset everytime?
Ohh I think that's what I just asked haha
this
If you don't want to serialize the field, then mark it non-serialized.
The inspector is used to configure an object. It's not intended to be a list of every single field the class has.
Okay, got it. Thanks for the help.
Hey, im using a roslyn code generator to generate this sample class right here:
using UnityEngine;
namespace EntityFramework {
public class ComponentList {
public static void Main() {
Debug.Log("");
}
}
}```
Whenever i generate it though it gives me this: https://img.sidia.net/ZEyI5/DOyUwaCa97.png/raw (Show references: https://img.sidia.net/ZEyI5/nozaRopu17.png/raw)
There is only one file, if I modify it by hand it is the same regardless of what reference i follow
This is the code generator: https://gdl.space/tozaqozoke.cs
Hey, Im using URP and I have a Camera which is disabled and I render its view to RenderTexture using camera.Render().
The problem is it renders Gizmos as well. How can I prevent it?
just for info, for the ppls who need it too...
i found a easy way to solve the problem!
so if anyone need it and dont wanna use third person assets, just ask 🙂
why do we use InvokeRepeating() in void Start() instead of void Update()I never understood the reason behind that.
I don't understand.
You can use it in either
But probably shouldn't use it at all
Use coroutines instead
Or just CALL the method in update I guess
i got no clue what those are, I'm just following the Junior Programmer pathway in Learn Unity
and for some reason they use invokerepeating in start rather than update
like it can still be multiplied by time.deltatime so i dont understand why that is
Well that is the opposite of what you said originally. Doing it in start makes more sense. Start tins once
oh wait, does invokerepeating just keep on running forever if it's called just once?
read the documentation for the methods you are using
InvokeRepeating and Execution stuff
you should get used to doing this; using tools without actually knowing what they do is going to make game development completely miserable
that is surprisingly simple
alright, thank you!
i will keep that in mind
Hi devs! I don't suppose someone could impart their wisdom and help me with something? I am trying to make my first person character controller work with an Xbox controller. I have everything working with PC but when I connect my controller, my movement and jump is already set up, but I need to find a way of getting the right analogue stick to work with the camera. Would anyone be able to help me out with getting this to work? I'm hoping that once learning this, I can teach future students with this method for their projects 🙂 TIA!
With the new or old input system?
New input system 🙂 I’ve tried to follow tutorials online but nothing seemed to work!
The channel for that is #🖱️┃input-system ;)
First time using the Discord, still navigating everything! 😄
I'm wondering, is there some way to programatically change width and height of a RenderTexture with a downscaled resolution (e.g. 192x108 for 1920x1080 display) whilst keeping the size same for just larger scales of a resolution (e.g. still 192x108 for 3840x2160)?
I don't understand what the goal is here. Don't you just want it to be a constant 192x108, then?
Or do you want lower values for smaller initial resolutions?
I want it to be 16:10 when the display is 16:10
Looks like RenderTexture.width and height are both writeable.
you can also just make a new one based on some calculation
oh, so you want a fixed aspect ratio
with a roughly constant total amount of pixels?
so you need to solve for width * height = total and width * ratio = height
two unknowns, two equations
ok
width = height / ratio, so you get height * height / ratio = total
height = sqrt(total / ratio)
given that, you can get
width = total / height
there will be some rounding error here
so you might not get exactly total pixels
so I floor that?
I would round it, I guess
ok
a little Trash-Post...
just wanna show you the result from my inspector editor 😛
My NavMeshAgent AI follows a waypoint in the Update function, but if the Waypoints Y value is too high (over 2.4 I think) it stops following the waypoint. Is there a way around this?
Might wanna snap the waypoint position onto the navmesh with NavMesh.SamplePosition
lol as soon as I posted this I thought about just making a new vector3 thats the waypoint x and z values only and Y is kept at 0 and it gives the result I want
thanks for your input though
I might use this actually instead of keeping the y value at 0
Likely this only works if your navmesh Y is near 0
So I would still use SamplePosition
Hi
is it possible to make a custom editor for classes that is not inherited from monobehaviour ?
Nope, you would need a custom propertydrawer
Unless it is a scriptableobject or something
@hexed pecan I just wanna mention it on other script
i have script called "Setup" which has a custom editor , inside this script I mention another class that is not monobehaviou public Writer writer; the custom editor of main has this line EditorGUILayout.PropertyField(writer); ... << this line is returning error "NullReferenceException: Object reference not set to an instance of an object"
I found that if I made writer a monobehaviour the problem is gone
Is Writer serializable?
also if I remove the custom editor the problem is also gone
I tried to add [System.Serializable] to it but instead giving me a spot where i can drag and drop the componenet, it gave me all variables in the writers
yes
Okay then Writer should be a MonoBehaviour or a ScriptableObject
Well, where would you drag it from if it wasn't a mono or SO?
ohhh good point
ok thank you so much ^^
but its kinda odd tho as without custom editor i can drag and drop it even if it's not monobehaviour
i thought something is missing in my editor
Not sure
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Hi, I'm really not sure where to ask this or what to do about it, so I'm asking here. I'm trying to lerp the feet's position to anchors that follow the hips after they reach a certain angle difference. The first problem I have is managing correct movement timing; I'm looking to make each feet move if the opposite is grounded. I also have issues with moving the character while lerping the feet, as they use an incorrect world position, and makes feet go to an old position. The last issue can seen at about 00:46.
Currently using animation rigging for the head, neck, and hip look direction, and code for making the feet face the correct direction. Any help or tips are greatly appreciated :)
thinking of implementing a restart button intra scene: can I just do my script for go to x scene and choose the current one and it'll restart? we have no other scripts to save from scene to scene so i'd imagine it would just restart if I do this, but I'm new to unity so im not sure
Yep, telling the scenemanager to load the current scene will reload it
link it inside the inspector so you know its fully connected
hey, thank you, but I´m not sure, what you mean by that?
Everything else is working fine with the slider. I just want to know how to access the navigation.
Ohh I never used that in script sry
thank you anyway, the visuals ony allowed one 😦
Hi. I want to make a card game and I'm having trouble with revealing cards.
They're supposed to reveal in a certain order, but they all get revealed at once. I tried putting WaitForSeconds(), but they still get revealed at the same time.
This is the loop that handles this. The Reveal() function just flips it and makes the parameter isRevealed true.
for (int j = 0; j < cardCount; j++)
{
GameObject localCard = cardSlots.transform.GetChild(j).gameObject; //Find the unrevealed card
if (localCard.GetComponent<CardProprieties>().playedOnTurn == currentTurn.Value)
{
yield return new WaitForSeconds(1); //wait 1 second
localCard.GetComponent<CardProprieties>().Reveal(); //Reveal card
int cardPower = localCard.GetComponent<CardProprieties>().currentPower;
if (side == 0)
{
location.GetComponent<LocationClass>().localPower += cardPower;
}
else
{
location.GetComponent<LocationClass>().enemyPower += cardPower;
}
}
}
yield return new WaitForSecounds(1);
Will only work by using a Coroutine
That for is in a coroutine
I have a problem and I want to know if someone can help me. I have a GameController that use Singleton so it has the DontDestroyOnLoad(gameObject); code. But when I change from one scene to another scene that have a GameController, the new GameController is replaced by the GameController from the scene before. This provoke that all the references from the objects in the new scene that use methods of the GameController are broken and missing. Sorry if this is a bit confusing, but if someone understand it, how can I solve it?
what singleton class are you using?
https://github.com/LoupAndSnoop/GenericDataStructures/blob/main/Singleton
Try this singleton
That's is how I create my Object
- that is why is is destroyed
- use the singleton class I sent you
it would be
public class GameController : Singleton<GameController> {
this singleton derives from monobehaviour
Ok, I will take a look of it, thank u so much
I see how it works, is a compact but so clever solution. Thank u again for sharing your work
ty. i got it from someone else, and made small modifications to it
That's remarkably similar to my SingletonBehavior
Wow heh.
using UnityEngine;
using JF.Logger;
namespace JF.UnityCore.Behaviour {
/// <summary>
/// A singleton Monobehaviour that automatically creates an instance of itself the first time instance is referenced
/// </summary>
abstract public class JFAutoSingletonBehaviour<T> : MonoBehaviour where T : MonoBehaviour {
public static T instance {
get {
if (_instance == null) {
// First try to find the instance in the scene.
_instance = FindObjectOfType<T>();
// If the instance doesn't exist, create a new gameobject and add the component
if (_instance == null) {
GameObject obj = new GameObject(typeof(T).ToString());
_instance = obj.AddComponent<T>();
}
}
return _instance;
}
}
private static T _instance;
virtual protected void Awake() {
if (_instance == null) {
_instance = this as T;
} else if (_instance != this) {
JFLogger.Error(
new string[] { "JFAutoSingletonBehaviour", typeof(T).ToString() },
"There can only be one instance of type {0}. This MonoBehaviour will be destroyed", typeof(T).ToString()
);
Destroy(this);
}
}
}
}
Like, eerily similar haha
Hey guys. Asked this a couple times before but got no solid answer. Lemme try again... Does anyone have any idea how to fix this?
hastebin link is dead now but i could resend if needed
i recommend having a special break for if the application is quitting, because you can get infinite loops when closing from things calling GetInstance as they are being destroyed
Yeah i see that in the other example
my game had some infinite loop crashes as it closed instead of closing properly as a result
You know, I have had a couple infinite loops for no reason recently
That will do it
that is why i also have TryGetInstance
TryGetInstance tries to get the instance, but does NOT try to make a new instance if it can’t find it.
I only call TryGetInstance in things like OnDisable, OnDestroy, and related to avoid infinite loop shenanigans
I appreciate the examplanation, I'll add it.
one last little thing: a lot of people like their singletons to be automatically DontDestroyOnLoad
My game has >50 singletons, and only 2 are DontDestroyOnLoad
Yeah, I just usually put it in Awake of the singleon itself
override protected void Awake() {
base.Awake();
DontDestroyOnLoad(this);
}
Yeah. Definitely do NOT copy that from my implementation. I’m stuck with it because I don’t want to refactor.
Haha you could refactor in like 20 mins if you bite the bullet 😄
yeah, but i don’t feel like it lol
the only parts that are actually important are the ones i mentioned about app quit and trygetinstance
Yeah I added those to my like 7 year old file, thanks! 😄
I think I've gotten kinda lucky since I don't often tear these down
Is there a specific component needed for TMP Input Field to work?
i put down a gameobject with a TMP Input Field component, but I think there is something else missing
create it from the asset menu
Perhaps a silly question here: do I need to cache results from Addressables.LoadAssetAsync, or will unity handle that?
In this tutorial, you'll learn several ways to load addressable assets into your game and how to release them from memory, using scripts. We've included some resources and reviews of scripting concepts that you'll use with the Addressables system. By the end of this tutorial, you'll be able to do the following: Define an asynchronous operation I...
m_LogoLoadOpHandle = Addressables.LoadAssetAsync<Sprite>(m_LogoAddress);
m_LogoLoadOpHandle.Completed += OnLogoLoadComplete;
private void OnLogoLoadComplete(AsyncOperationHandle<Sprite> asyncOperationHandle)
{
if (asyncOperationHandle.Status == AsyncOperationStatus.Succeeded)
{
m_gameLogoImage.sprite = asyncOperationHandle.Result;
}
}
Not exactly. I mean what I load the same asset many times (say a reused tree prefab)...
Hey all. I'm trying to setup object pooling for the first time and this was my attempt at setting up a system that allows for it to be relatively expandable with multiple pools, curious on your guys' opinion. Whether i've done any bad practices, how I could potentially improve, etc. Thanks
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public sealed class ObjectPool : MonoBehaviour
{
public static ObjectPool instance;
private void Awake()
{
if(instance == null) instance = this;
}
[System.Serializable]
public sealed class Pool
{
[HideInInspector] public GameObject[] objects;
public int count;
public GameObject prefab;
public string identifier;
public void CreatePool()
{
objects = new GameObject[count];
for(int i = 0; i < count; i++)
{
GameObject obj = Instantiate(prefab);
obj.transform.parent = instance.transform;
obj.SetActive(false);
objects[i] = obj;
}
}
public Pool(string identifier, GameObject prefab, int count)
{
this.identifier = identifier;
this.prefab = prefab;
this.count = count;
CreatePool();
}
}
[SerializeField] private List<Pool> objectPools;
private void Start()
{
foreach (Pool pool in objectPools)
{
pool.CreatePool();
}
}
public void AddPool(string identifier, GameObject prefab, int count)
{
objectPools.Add(new(identifier, prefab, count));
}
public GameObject GetPooledObject(string poolIdentifier)
{
Pool pool = objectPools.FirstOrDefault(p => p.identifier.ToLower() == poolIdentifier.ToLower());
if(pool == null) return null;
return pool.objects.FirstOrDefault(obj => obj.activeInHierarchy);
}
}
https://docs.unity3d.com/ScriptReference/Pool.ObjectPool_1.html
there is already an object pooling class, very easy to implement
if you wanted to stay with yours,
i suggest getting away from using a string for the ID. Maybe you can just use the prefab as an ID
then you can use a Dictionary<GameObject, Pool> instead of having to search through a list to find the pool you want
Oh alright, thank you.
The issue with this was that it wouldnt let me serialize a dictionary, but i suppose i could use a struct
also instead of checking which is activeInHierarchy, you can keep a collection of objects only usable in the pool. Remove them from the pool as they are gotten, then have them returned when they are finished being used. This way you've immediately gotten rid of searching through objectPools and searching through the pool itself
there are serialized dictionaries online, but you could use a list for the editor and build the dictionary based on the list. The dictionary itself doesnt need to be serialized
Makes sense thanks again
Do you mind explaining how i would go about using a prefab as the id, what property of it should i use?
any property of it that you want, you could just directly do Dictionary<GameObject, Pool> or Dictionary<Component, Pool>. Then you dont need to search for an ID cause its just
objectPools[GameObjectThatIWant].
ye should just stick to a specific type for each pool
Also its the same like how you are using a string for the ID, you could remove that string entirely and just compare the prefab
Pool<T>
public T prefab;
Gotcha, working on implementing it now
It's more that GameObject itself is pretty ambiguous, even if you know what's to be stored in it. Usually you want pools to be quick and direct at what they're distributing.
Finer control. But if you're new, a rigidbody is "easier" to move, you just point and launch it.
you can have more control over cc without worrying too much about collision detection
kinematic can give you control as much but then you need your own detections for wall
Anyone know why childRectTransformMaximumSize; is a different color than the rest? It is used shortly after this declaration
Bah. It is never actually used, even though a value is assigned in Start. i forgot i changed that calculation
yeah assigning a value doesn't necessarily mean its being used
CharacterController has other little goodies which rigidbody doesn't have
cc is good for if you want a player controller that does everything you want out of the box
UnityEditor.dll assembly is referenced by user code, but this is not allowed.
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)
can anyone help me for resolve this problem
i already did checked all my script for UnityEditor Reference or not ,, but after i resolve it , same error happen