#๐ปโcode-beginner
1 messages ยท Page 7 of 1
There should be typically not even be a copy of the prefab in the scene at edit time
btw [SerializeField] does not make a variable accessible from another script
I think he means he gets a reference to the script so he can access its data
Vector3 tgtMoveDir = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical")).normalized;
This seems jank, even if you have 0.001 on vertical, the normalized makes it so the moveDir is always of length 1. So maybe that gives you the idea that it's throwing you in a random direction?
yeah that one
im just using keys, so it is correctly 0,0,0 when it is meant to be
i also removed the normalise and the issue is still happening :(
so it seems to be zooming me in the opposite direction of the keys im pressing, and only when im mid-air
it just sometimes happens, sometimes it doesnt
Well, it's hard to tell then, because I don't know which if and which else it goes into, and I also don't know all the parameters you have set.
Also you talk about zooming which I guess means it throws you in a different direction, and not something to do with camera zooming. Maybe a video/gif is handy to describe the problem.
yeah as in increasing my velocity and sending me flying away
Looks like I already did that.
Below is the code where I instantiated Boost(booster).
"ballpos" is the cube.
Now I need to use "On trigger" function on booster(Set to "Is Trigger" ON) but it must be triggered by ballpos(cube)
How to do that?
This script belongs to another gameobject(a gameobject I used just to keep the script alive, and the gameobject is "empty")
Add a bunch of Debug.Logs in your code, and see which vector is super high then. Then you can work backwards on why it does that.
Your lateral velocity goes insane, which seems derived from your normal velocity.
So add a debug.log for all the vectors in your AddForce methods.
oh i found the specific thing
so, its only on the Z axis, if i start a jump going right, then press the left button, it zooms me
so if i try to change my direction midair
ive removed the multiplier and its still an issue
if (rbLateralVelocity.magnitude > tgtSpeed) rb.AddRelativeForce(-tgtMoveDir * (rbLateralVelocity.magnitude - tgtSpeed + addSpeed * multiplier), ForceMode.Force);
Also, this is weird, if your magnitude is high, you add more force. Maybe comment out that line.
yeah, yeah
i did that and added the inverse of that if statement to the else above it
seems to be working fine now
i am just a little silly
https://hatebin.com/lamunjbvmq hey everyone. This is my script. The issue I have is that my character goes up and down in a straight line when I jump. It does not seem like a real jump If i make myself clear. How can I achieve that realistic jump look?
oh, wait, you're not doing it that way, uhm, standby
Oh, and I misunderstood - you're not talking about horizontal movement issues, you're talking about linear up/down - ie, gravity not being applied.
Your issue is that you're just adding "gravity times time" to your y position. You're already using a collider so if your level is all setup with rigidbodies, just enable gravity on your player object and change the bit of code in jump() from trying to do gravity yourself to just applying a one time upward force
how can I get the position of the gameobject trough mouse click? this is what I try but failed https://hatebin.com/ybuivjiabt
I would use Plane.Raycast here
I dont have anything with rigidbody in my game
ah will try thx
I thought character controller and rigidbody didnt go well together
e.g.
Plane p = new Plane(Vector3.up, Vector3.zero);
Ray r = Camera.main.ScreenPointToRay(Input.mousePosition);
p.Raycast(r, out float enter);
Vector3 worldPoint = r.GetPoint(enter);
Vector3 cellCoordinate = tilemap.WorldToCell(worldPoint);
Vector3 cellCenterWorld = tilemap.GetCellCenterWorld(cellCoordinate);```
tyvm
can you show a video? wdym up and down
isn't that wat a jump iss?
you're right.. I don't quite see at a glance what's wrong with your script though, but it's a little confusing.. like why are you setting the y velocity to -2 when the player is grounded? why are you multiplying a bunch of constants when the player jumps? why are you multiplying y times delta time and then again setting velocity times deltatime in Move()?
most of the code is similiar to the example of CC move
https://docs.unity3d.com/ScriptReference/CharacterController.Move.html
Setting the velocity to -2 just so there is still gravity when its grounded. I thought I should multiply the gravity in jump method to have them applied? So I could fall down I think
yes
i'd also make sure your IsGrounded() is actually retruning false while the player is in the air, since you are checking to see if the Y velocity is < 0 (then setting it to -2??)
if your isgrounded is returning true then your player is going to "float" down at y velocity = -2 no matter what
Can I post the video in this channel?
yes
I should just remove that line then?
I dont double jump or anything
should be mp4 format
looks fine to me. Maybe try reducing the gravity multiplier?
probably that much gravity doesn't help either
can I send another video?
sure
Fine to me as well. Also a cool trick if you using a cube when jumping you can rotate it in a Z or X axis depending which direction the cube faceing. So when you jump it also do a little "flip". A nice touch but adds more to the jumping vibe! ๐
Ah cool. Thanks ๐
how i alter this to give exact same results for each player
if (Physics.Raycast(allparticles[i].position, allparticles[i].velocity, out hit, allparticles[i].velocity.magnitude * Time.deltaTime, 1 << 0))
hey guys i have a project a platform game and i need to know how can i set a game over when the player jumps into the void can someone help me
i already made a box collider 2d outside of the camera
Does not it feel a little like not jumping but just moving upwards or am i tripping
It was fine to me as well but a friend said so and im not sure anymore ๐
Make a UI for the game over, hide it and when collison happens (ontriggerenter2d) setactive to true for the game over ui. also take away the control from the player with a simple bool. make sure to use using Unity.Engine.UI;
I make a separeted script for the game over ui?
on second tought, its better to monitor the player Y coords and make a if statement if it reach a amount then trigger the game over, so you dont need to make a veeery long box collison for that.
I already make it and make the if for the the ontriggerenter
I just don't know how to continue
Make a UI first then hide it.
On the player inside the update method write:
if (transform.position.y < -20)
{
Debug.Log("Game Over: Player went off the screen.");
playerAlive = false;
gameOver();
}
make sure to have a bool playerAlive = true; then have a gameover method that will trigger the gameover ui with ex. gameOverScreen.SetActive(true);
Working on a simple weapon recoil system from my gun. Ive followed tutorials for weapon recoil and tried a bunch of different ideas, but most seem to implement a system that just rotates the camera up and then back to the origianl position. Im more lookin for a way to just bump the camera up by a rotation so the player has to reset the camera. Ive been goin over this since yesterday afternoon to no avail unfortunately.
private Vector3 targetRot;
[SerializeField]
private float recoilX;
[SerializeField]
private float recoilY;
[SerializeField]
private float recoilZ;
[SerializeField]
private float snappiness;
[SerializeField]
private float returnSpeed;
void Start()
{
}
void Update()
{
targetRot = Vector3.Lerp(targetRot, Vector3.zero, returnSpeed * Time.deltaTime);
currentRot = Vector3.Slerp(currentRot, targetRot, snappiness * Time.fixedDeltaTime);
transform.localRotation = Quaternion.Euler(currentRot);
}
public void RecoilFire()
{
targetRot += new Vector3(-recoilX, Random.Range(-recoilY, recoilY), Random.Range(-recoilZ,recoilZ));
}```
with the current looking result lookin like this:
(this has easily been the hardest part of the project so far
, I can't wrap my head around what to do here)
Can I call you in private to explain better? And show u my code?
this is probably a dumb question, but here I go.... when I make an abstract class - lets call it "customEvent"
and then make multiple classes that inherit from it - "customEvent1", 2 and so on
can I put those classes into a collection of some sort, so I can loop through them efficiently?
yes, make a collection of the abstract class then anything which inherits from it can be placed inside
yes
And is this a dumb implementation or an actually decent practice?
normal practice
Hopefully your classes are not actually called customEvent and customEvent1 etc
lol
Nah, it was just an example haha
A typical example would be like:
abstract class Fruit {}
class Apple : Fruit {}
class Banana : Fruit {}
List<Fruit> fruits = new();
fruits.Add(new Apple());
fruits.Add(new Apple());
fruits.Add(new Banana());```
fyi, works for interfaces and all inherited classes as well not just abstract classes
I feel like I am missing something.
within the update I have a method.
within that method there are if statements..
when the if statement isn't true anymore the method is still running within the update.. I don't know what I'm not seeing.
The method will run
the stuff inside the if will not run whent he condition is false
if the method is running unconditionally, it will always run
if only controls stuff inside its brackets
I've heard about interfaces a decent amount but I actually am not sure what they are about, more reading to do I suppose
public void FootballFollow()
{
if (!football.activeSelf && footballFollowing.activeSelf)
{
football.transform.position = following.transform.position;
Debug.Log("Follow");
}
if (!football.activeSelf && !footballFollowing.activeSelf)
{
football.SetActive(true);
var stopFollow = following.transform.position;
stopFollow.x += -3;
football.transform.position = stopFollow;
Debug.Log("Dont follow");
}
else
{
return;
}
is anything in here wrong?
Hard to say if it's "wrong" without knowing the intention
I assume that your assumptions about what is true and what is false are incorrect
use Debug.Log to check
So, let's break it down line by line.
if football is inactive, and footballFollowing is, it does the first one.
Then, if neither are active, it does the second one.
In all other cases, it does nothing
correct.
e.g.
Debug.Log($"football active: {football.activeSelf}, footballFollowing active: {footballFollowing.activeSelf}");```
(put this as the first line in the function)
Also turn off collapse so you can actually see the order the messages are coming
I will use that. I am just confused.. because in the scene view as they are disabled and enabled
it lines up with what I want.. but when they are both disabled.. the states don't reflect that
even though within the scene they are clearly disabled
The issue is, I kinda need to be able to serialize the list and be able to edit the variables of each of the inheriting classes outside of playmode, which makes me feel like this is a dumb approach
make sure you're not confusing activeSelf with activeInHierarchy
unity serialization doesn't generally support polymorphism, especially not in the inspector
wow.. didn't even know that was a thing
you could do it with Odin inspector
Are they disabled, or is a parent object disabled
Is this script on one of the disabled objects
is the Character Controller has it own collider? If i put it on my player i cant got through walls but if i put it on a npc, they can go through walls.
It's not so much that it has a collider than it is a collider
Yeah, I guess it is
So when its disabled the function isn't running at all
so why does npcs enter ghost mode? xd
How are you moving the NPCs
transform.position += transform.forward * moveSpeed * Time.deltaTime;
So you're not using the character controller at all
you're teleporting
that's not going to respect any collisions
Thank you, I gotta put it on another object I suppose
teleporting pixel by pixel you mean?
Well, teleporting by moveSpeed * deltaTime
but teleporting nonetheless
My use case is - I have X amount of possible events that could happen (eg. Lights go out) and I need to trigger them randomly - could I, in theory, define abstract class of the event, make a class that inherits from it for each and serialize them outside of a list, just as separate variables and then have the "current event" variable set as the original abstract class type, so I can store any of the events that inherit from it inside?
Does that make any sense at all or am I out of the loop completely?
So even though the script is still checked on the right in the inspector, the stuff isn't running because the object is disabled?
Disabling an object also disables all components on it. Disabling a parent object also disables all child objects, which in turn disables all of their scripts
Basically, disabling a thing always disables all the stuff under it automatically
Ok, the fact I saw the other stuff still checked.. I didn't understand that
maybe you're overcomplicating this. Can these events just be represented by an enum perhaps?
enum SpookyEvent {
LightsFlicker,
LightsGoOut,
Thunderclap
}```
Thank you
and then just have a List<SpookyEvent>
and pick a random one from there?
then you can determine the actual behavior with a switch or a Dictionary keyed on the enum to a delegate
So how does a AI usually move? i have this script on it which moves (well pushing) in a random direction. https://paste.ofcode.org/Q3dTx8Xvfazm9gNia8MFGE
That's why there's two different values, an object can be "Directly Disabled" or "De Facto Disabled" when one of the things containing it is disabled. ActiveSelf and ActiveInHierarchy
If you want it to use a CharacterController to move, you should use the CharacterController's .Move
depends entirely on the requirements of the ai in question. There are many ways to move things. If you want the motion to respect physics, you'll have to move it in a physics-aware way.
such as with the CC
these events will have the player do something, thats why I though an enum wouldnt be enough
like, when lights flicker, you need to turn the switch off and on
they are also kinda all over the place - the event could be related to lights, sounds, objects and so on
right but
you can separate that behavior from the choosing and representation of those events
especially if you want to represent it in the inspector for examplke
though I guess maybe you want parameters for all these things
Alrighty, i will look into it. thanks for the info.
I think I solved it, I just made a 3rd game object that controls the other 2.. that way I can actually turn them on and off without the script being disabled. I spent a bunch of time trying to figure out what was wrong.. So I really appreiate all of your help..
you are right that I am probably overcomplicating, Im trying to find a balance between maintainability and modularity
Debug.Log(parentTransform.gameObject.name);
stats = parentTransform.GetComponent<Stats>();
if (stats == null)
Debug.LogError("Stats component not found on parent.");``` im trying to reach my stats script on the player gameobject from my charactercustomizer script but am getting null
Show the inspector of the NewPlayer game object
yeah im just now realizing that newplayer is probably throwing the error, forgot that one had the script aswell as i just used it to test some stuff
Seriously, thank you very much for your help. I was stuck not understanding whhy this wasn't working for way too long.
that was it ๐ , im just dumb:p
Does anyone know why this error is happening?
iโm getting a directory not found exception when trying to build
No luck yet, been looking
@wintry quarry I think the easiest solution for me will be a single event template class with a unityevent to handle the different logic of each of the events
Is there something that could cause Trail material input missing from the particle system after enabling trails?
generally my particle system doesnt show up trail material input under renderer component after enabling Trails component
var ballRandomLocation = new Vector3(Random.Range(-10.0f, 10.0f), 0, Random.Range(-10.0f, 10.0f));
So would I be able to use this in
stopFollow.x += ballRandomLocation;
What could be causing it to be missing?
Missing the trail material?
yeah mate but if u look its missing where i am supposed to place it
its usually under renderer right under Material
its not popping out and editor is not throwing any errors aswell
Is the public class missing?
?
Look in your code near the top of one of them that works. and compare it to the one that doesn't
What code, that is particle system
Oh im sorry
This code works completely fine. But someone told me that Quaternion Euler is too expensive or not to be used. Is this true? And if so, how do I change this code to make it less expensive?
I though i was in unity talk , sorry
{
football.SetActive(true);
Vector3 stopFollow = following.transform.position;
Vector3 ballRandomLocation = new Vector3(Random.Range(-2.0f, 2.0f), Random.Range(-2.0f, 2.0f), 0);
stopFollow.x = ballRandomLocation.x; // Assign the x-coordinate of ballRandomLocation to stopFollow.x
football.transform.position = stopFollow;
Debug.Log("Don't follow");
}
Any ideas?
cuz I don't believe it needs to be instantiating.. so the documentation on it isn't making sense
I don't know what you want to do, so hard to answer
System.InvalidOperationException: Cannot read minds through HTTP
haha
Sorry. Trying to use ballRandomLocation to choose a random location for the football.transform.position
football.transform.position = ballRandomLocation;
This actually is working now
since I updated it
I need to add the stopFollow.y = too
That's the long version but it works as well
{
football.SetActive(true);
Vector3 stopFollow = following.transform.position;
Vector3 ballRandomLocation = new Vector3(Random.Range(-2.0f, 2.0f), Random.Range(-2.0f, 2.0f), 0);
stopFollow.x = ballRandomLocation.x; // Assign the x-coordinate of ballRandomLocation to stopFollow.x
stopFollow.y = ballRandomLocation.y; // Assign the y-coordinate of ballRandomLocation to stopFollow.y
football.transform.position = stopFollow;
Debug.Log("Don't follow");
}
feels longer than it needs to be. I think you are right
hmm maybe not though
cuz I need the follow.
and the football.
- You don't need to store the position in the
stopFollowlocal variable - Yes you can assign the whole vector directly
Quick note on the issue i had, if anyone happens to have it in future, even though my editor didnt throw any error or warning, it was indeed bugged out and restarting editor fixed it ๐
Thank you for sharing that. Glad you were able to fix it with a restart
So, besides it being ugly and bad practice. Does dumb stuff like this hurt game performance?
No, unless you are doing it in update
At this scale no, even in Update
Worry more about calls to Find() and GetComponent<T>() in Update
Alright. But for future reference it's always best to correct things like this before it becomes a habit
it can hurt performance on low end devices dont be fooled, anything in update can get heavy, so it depends for what platform you are building for, if its for PC then its minimum impact
Copying a value type around is not
Good practice is to use update only when u must and for inputs
Usually if you want to have code repeat u use Coroutines instead , performance wise they are great
Been trying to wrap my head around this and I still cant figure it out. #๐ปโcode-beginner message
Im just lookin for a way to bump the camera up when firing and then clamp the camera rotation at a certain point once it hits that in the recoil
any suggestions?
When did you start getting this error?
if i start a coroutine, then disable the game object, does the coroutine still run?
don't ask to ask
no, the coroutine will end if you disable the object that owns it
that's a shame
i'll disable the sprite and collider then
i want my object to disappear and respawn after 2 seconds in different location
so wanted to start respawn coroutine, disble object
and hoped that it will re-enable inside that coroutine
if you call StartCoroutine on another object you could do that, it's just that a coroutine instance that is owned by a monobehaviour that is disabled will be disabled as well
well i dont really have where to call that
i have Square.cs and HealthSystem.cs
health system has TakeDamage() and when the dmg drops <= 0 i call RespawnSquare() function from Square.cs
public void RespawnSquare(float delay)
{
StartCoroutine(RespawnCoroutine(delay));
}
private IEnumerator RespawnCoroutine(float delay)
{
yield return new WaitForSeconds(delay);
SetSquareRandomPosition();
}
public void TakeDamage(int damage)
{
if (isDead) return;
currentHealth -= damage;
if(currentHealth <= 0)
{
isDead = true;
owner.RespawnSquare(LevelDataStorageManager.Instance.currentLevelData.respawnDelay);
}
}
Collider is on Square Object, and SpriteRenderer is under Graphics
i just hoped that i can somehow disable the root object
I probably could have some sort of "RespawnManager"
who will call the coroutines
but idk if its a good idea
Does anyone know who to fix this? it seems I can no longer make references to some libries like TMPro
just vs code things lmao
you could try regenerating project files. or you could consider switching to visual studio which is far less likely to randomly break
you could try Edit-> preferences ->external tools -> regenerate proj files
but yeah you should also use visual studio to avoid most of issues u can come across with vscode , plenty ppl here only asking how to fix this and that on vscode
I want to spawn a prefab in a random (visible) position. How can I get the "visible" area and spawn inside that area with some margin? so it doesn't spawn at the edge and half of the object is off camera etc
you can use layer to cover that area and then raycast untill u hit some point of that collider of that layer
I was also thinking at creating a box collider 2D and spawning inside that box collider
but idk if its good idea
Try, there is not one solution to ur problem, there are probably dozen
Ok I fixed this.
First I installed this package to VSCode.
Then back in Unity installed this package.
All is working well now.
yeah that's how you're meant to configure vs code now that microsoft has taken over maintaining the unity extension
I just don't know why is has to have visual studio editor installed when I use visual studio code?
because that is what creates the working project files for vs code now
you can uninstall the vs code editor package
The unity package in vscode wanted me to install it.
huh?
i'm talking about uninstalling the Visual Studio Code Editor package. the unity extension requires the Visual Studio Editor package now
literally the one right above the one you have selected in your screenshot can be removed
if I want to make a setting changing font of all text elements in my game what do I do
Sorry I misunderstood. Now I got you. Will I still be able to use VScode? Well let me try it out
yes. the vs code editor package is no longer required because as you have already discovered, the unity extension in vs code now uses the visual studio editor package
It was all working fine yesterday lol. It all makes sense now. Thank you very much! Appreciate it ๐
public void SetSquareRandomFreePosition()
{
//Dangerous loop, yet I don't have other idea for now
while (true)
{
var randomPos = GetRandomVisiblePosition();
Collider2D[] squaresNear = Physics2D.OverlapCircleAll(randomPos, squareSize);
if (squaresNear.Length == 0)
{
transform.position = randomPos;
break;
}
}
}
I am spawning a Square in a random position inside the Camera, then I am doing a check if there are no other Squares near the possible spawn position, so I am only spawning the squares in free positions, althought it doesn't work and squares spawn on top of each other, why?
help me please
I'm trying to make a slide, but when I click the C key, the player scales down, but it doesn't go forward with the rigidbody, can you help me with this?
Maybe tell people what's wrong
I tell
Here
you can help me?
Without scaling, does it go forward with the rigid body?
I want to do the following, I want the player to scale down, and be propelled forward
Does it work without scaling?
If it doesn't work without the scaling, it won't work with it.
I don't know about the rigidbody, but the slide doesn't work without reducing the player's scale
Comment out the scaling and see if the player propels forward
ok
the player is not advancing
So fix that first.
does anyone here have much experience with the kiwicoder free behavior tree?
I'm attempting to add my own nodes but am having trouble assigning gameobjects and other classes as NodeProperties...
(for example adding a target object for a moveTo node keeps yielding a "Type mismatch" error when putting in a G.O with the valid type / class)
Ive even tried to circumvent it by searching for the target object using GameObject.find and pulling data from there but it just spits out the property anytime I attempt to use it.
how?
Maybe the if statement is never true or maybe the coroutine is never started
this is my rigidbody of my player
maybe due to using overlap circle, yet these shapes are boxes
yes, it is being started, because the player's scale changes but it is not propelled forward
Kinematic rigidbodies do not react to AddForce()!
no, it's not related
I recall kinematic disabling physics add force
You activated it, compared to your prefab
"Is Kinematic" is in bold, showing that it's overriden compared to the prefab
@eternal needle why are you reacting
OverlapCircle2D is just a method that gets all coliliders inside the sphere
If I disable "Is Kinematic" my player starts to wander
doesnt matter if i have BoxCollider2D lmao
You talk to me?
do you know what a circle looks like by chance
Yes
Disable kinematic
it is not related... Physics2d.OverlapCircle2D is just for getting colliders inside a certain radius from a certain point. It can detect BoxCollider2D aswell
And it will react to forces fine
@short hazel
Then you have code applying force elsewhere
and i never said it cant detect boxcolliders.
alright ill pull out the paint drawing..
Are you sure your squareSize is correct?
No?
yes its correct
So, I just disabled "Is kinematic" and it worked!, but my player is going down ramble
i understand what do you mean @eternal needle but even when putting hilarious big radius number like 10
it still doesnt detect
I'm using Unity's Standard Assets
No, they're saying that the overlap circle and the visuals of the object aren't going to match exactly
my square size is 1 units, i want to do overlap circle with 2 units from square center
even if i put like 100 radius it still spawns on top of each other
how I can fix the poblem?
this is what i was referring to. But based on what you said above, you should add debugs or gizmos and visualize the overlap function to see if its in the correct place
yea i understood what you meant sorry for the confusion
Are the squares colliders or triggers
maybe add this to your box script
private void OnDrawGizmos()
{
Gizmos.color = Color.green;
Gizmos.DrawWireSphere(transform.position, squareSize);
}
to see the cricles
is the weapon
hey guys I'm new to unity and i need some help. so the thing is I'm working on a prototype based on marvel snap and i need to make it work multiplayer as well as playable with AI. for this case I'm using 4 lists
- Player Owned Cards
- Used Cards (Player)
- Enemy Owned Cards
- Used Cards (Enemy)
is there any way i can use the lists outside the class by using interface which behaves as an AI as well as the player
alr
tf does that mean? The player code obviously, where you're adding other forces for movement, for example
When I disable "Is kinematic" unity debugs an error for me, this is the error @short hazel
are they all at the same Z position?
let me share some more code I have SquareSpawnManager with functions:
private void Start()
{
Camera.main.orthographicSize = LevelDataStorageManager.Instance.currentLevelData.cameraSize;
SpawnInitialSquares();
}
private void SpawnInitialSquares()
{
remainingSquares = new List<Square>();
for(int i=0; i< LevelDataStorageManager.Instance.currentLevelData.squareCount; i++)
{
Square square = Instantiate(squarePrefab);
remainingSquares.Add(square);
square.SetSquareRandomFreePosition();
}
}
and Square
public void SetSquareRandomFreePosition()
{
//Dangerous loop, yet I don't have other idea for now
while (true)
{
var randomPos = GetRandomVisiblePosition();
Collider2D[] squaresNear = Physics2D.OverlapCircleAll(randomPos, squareSize);
if (squaresNear.Length == 0)
{
transform.position = randomPos;
break;
}
}
}
@short hazel
all on 0
Can you be patient while I type lol
No need to ping every 15 seconds
Add this log after your overlap:
Debug.Log($"{gameObject.name} is checking a circle of radius {squareSize} around {randomPos} and found {squaresNear.Length} collisions.");
kk
Does your circle have a collider?
^ yes
result
Sorry then. When I deactivated the weapon, the problem still continued, so maybe that's not the problem.
Non-Convex MeshColliders with Non-Kinematic Rigidbodies is no longer supported since Unity 5
Looks like your weapon model has an issue, the mesh collider on it is not convex, but it should be, as per the error
Standard Assets is deprecated, it has been replaced with the newer Starter Assets
yes
they stack a lot ๐
ok, and?
how I can fix?
Dude
Can you show the inspectors of two of the objects that are overlapping? Any two.
sure
There's literally a check box that says "Convex" on your mesh collider, you need to check it
I a new in unity, I'm sorry
thank you
Thanks, I managed to solve the gun problem, but the player keeps crashing
is there a problem with spawning the Squares in a for loop? maybe they aren't processed yet or something, i dont know i feel lost
private void SpawnInitialSquares()
{
remainingSquares = new List<Square>();
for(int i=0; i< LevelDataStorageManager.Instance.currentLevelData.squareCount; i++)
{
Square square = Instantiate(squarePrefab);
remainingSquares.Add(square);
square.SetSquareRandomFreePosition();
}
}
I think what might be happening here is that they all check their locations at once, and no one is around yet. Then they all confirm their destinations are okay, then all teleport there together.
Maybe this is the problem?
but why tho when it's in a for loop
so it should do one iteration
then another one etc
Maybe? Disable that and run the game, see if the issue still occurs
I'm guessing there's a delay between when an object moves and when its collider "catches up" due to one moving in Update and one moving in FixedUpdate
I'm not sure how to fix, but I'm thinking
At least trying to think of a way to see if this is happening
public void SetSquareRandomFreePosition() make this a bool
and coroutine
and WaitUntill?
in the spawn loop ?
the spawn methdo as a corotuine*
Yeah, that should do it actually
let me try
The problem disappeared when I disabled that script, so the problem is in the script, what now?
private IEnumerator SpawnInitialSquares()
{
remainingSquares = new List<Square>();
for(int i=0; i< LevelDataStorageManager.Instance.currentLevelData.squareCount; i++)
{
Square square = Instantiate(squarePrefab);
remainingSquares.Add(square);
yield return new WaitUntil(() => square.SetSquareRandomFreePosition());
}
}
let's see
Make sure you do not have a controller plugged in, or something that could give input without you knowing. Yes, steering wheels also give input, even when not touched.
Then fiddle with the stick to ground force and gravity multiplier. It might be holding down the rigidbody too hard, creating ghost forces
well, i can defo see the progress but they are still overlapping (not as much as before tho and not that often)
here?
i think it'd be easier/better if you stored a list of positions then try to spawn them based on the list rather than overlap functions
i did another yield wait for fixed update
lits of random positions?
the list of objects already spawned
ow
Ah, that's an issue I see here. You cannot have a Character Controller and a Rigidbody or Collider on the same object, they will conflict with each other
ok, how do I solve it? which one do I take from the player
i already have a list of spawned squares
so i can just read their position
and do a distance check
if you want it radius based then yea that could work. you could use sqr magnitude instead and just compare it to the (squaresize * squaresize) so you save yourself a sqrt call
but i feel like
it would be heavy for performance
Whatever the First Person Controller script requires. And before you ask, no I don't remember which one it uses
because i have levels with 500, 600, 700 squares
so if im spawning square number 400, i have to loop through all previous squares
and compare distance
and if none is near then spawn
How am I going to solve this?
i cant imagine spawning 700 squares and doing 700 overlap functions would be much better. still this is a large amount of objects, its not gonna be instant unless you remove the randomness part and spawn them differently
By reading my message again and researching what the script requires
without the rigidbody, the slide doesn't work, and without the controller character the player doesn't work
but when spawning 700 squares, im doing 700 overlaps and thats it
but then i have 700 squares with distance checks
and spawning square 699 i have to do forlopp for 698 already spawned squared
and next iteration spawning square 700 i have to do forloop for 699 already spawned
etc
I dont know
YES, I not find
Well, an alternative would be to remove the rigidbody, collider, character controller, first person controller from the object, and adding the first person controller again
If it's well made, it'll add the required components by itself
Guys Microsoft Visual Studio is so crashing, should I use another IDE like Visual Studio Code? or keep the purple one
dont you want to SetSquareRandomFreePosition, and then add it to remainingSquares?
What kind of crashing ?
Lagging, PC goes slow
Are certain is directly related to Visual Studio ? What kinda specs u got
just a quick example for context. On the bottom the ball would be bouncing along only the x axis. But since this is simulated 3d space.. the example on the top is more of what it would look like. Has anyone ever attempted this. Wondering about trying to get gravity to work in this way. If not using gravity, I think just keeping a hitbox where the red circle is and faking depth using animations is the way to go.
does this belong here(or in #๐โanimation)
I wrote them on my bio
๐คท try viscode then.
If it runs better use that instead as long is itโs configured w Unity.
Okay
because the purple one gets 2GB ram
which is the half of my RAM
ok thanks for helping, bye

Poor computer, has 4gb RAM and Windows requires at least 2 by itself to work properly
Time to throw good ol windows XP on that ish
man i've been struggling with 16gb recently. i can't imagine going back to 4 ๐ฑ
What would you call the thing I'm trying to do.. just so I know what to research? moving an object in 2d space simulating 3d? Just don't know I should word it
can you elaborate on what that means?
I think just keeping a hitbox where the red circle is and faking depth using animations is the way to go.
yeah that would probably be the way to go
unless of course you want to actually use 3d objects and physics
the "and physics" was also in reference to "3d"
i feel like this isn't really a code question anymore
Good point. Thank you for your help
Hey guys, I was wondering how I could tie two values to each other? Trying to tie a mesh's colour to a value but unsure how to do it. here's a code snippet: ```CS
// time (s) to reach peak value currently = 5
ballMesh.material.color = Color.Lerp(ballMesh.material.color, Color.red, time);
// colour needs to be peak (ie fully red) at x seconds. x = 5 in this case
If time is the time in seconds since you started lerping, you'd do time / x for it to reach the destination after x seconds
I tried that but it doesn't work. it never reaches max "redness". There's also an inverse function that lerps back from red to a default colour, but by doing time/x also stops it from returning to default
once the time reaches the duration, you manually set the value at the end . . .
but I could do that without using lerp, it would just be an instant colour change
when I say it doesn't reach max colour, i mean it's quite off
not buy say 10 in the red channel
Hey guys, Ive been stumped really bad with this recoil system Ive been trying to implement. Ive been at this for two days scouring the web, but to no avail. Im trying to add in a basic weapon recoil system that gets recoils up when a gun is fired, but have not been able to find a guide or suggestions on how to do it. Most guides are for fully automatic weapons that reset the camera after firing is complete (which is not what Im lookin for). #๐ปโcode-beginner message any suggestions?
so you want a system that recoils up, but leaves it to the user to recentre?
can't you just follow the guide and just ignore the recentring code?
Ive tried that
I pretty much have the same code on my end for recoil, and it works
You sure there's no other scripts that set the rotation directly, and could override what the recoil script does?
my current implementation unfortuneately spins the camera around the character if I do that
so Im trying to figure out how to clamp it at a certain rotation
The clamping would be done before you add the recoil to the vector
{
targetRot = Vector3.Lerp(targetRot, Vector3.zero, returnSpeed * Time.deltaTime);
currentRot = Vector3.Slerp(currentRot, targetRot, snappiness * Time.fixedDeltaTime);
transform.localRotation = Quaternion.Euler(currentRot);
}
public void RecoilFire()
{
targetRot += new Vector3(-recoilX, Random.Range(-recoilY, recoilY), Random.Range(-recoilZ,recoilZ));
}``` so in my current implementation, would I clamp the targetRot in RecoilFire() or in update? or clamp currentRot?
Hey, im trying to work with the kiwicoder behavior tree, and im running into an issue where it wont accept public / serialized properties from the inspector. I dont know if anyone can provide some advise or if I'm just going to have to pony up for a real BT asset.
The issue is a little tough to but into writing but in short, its just like making a public or serialized property in a normal script, where it appears in the inspector and you can select an object of a specific type from the field. Except when you select an object from that field it errors out and says that there is a type mismatch, when you literally can't select an object of the wrong type
heres a video of it as well
https://cdn.discordapp.com/attachments/1146187317502029917/1154870484362612736/20230922-2002-19.6366722.mp4
ignore the poor naming, I did this in a different project to double check it wasnt a bug caused by a bad library
In RecoilFire. It dirties the code a bit since you need to apply the clamp for whatever axes you need, but it would look like this
// note the absence of '+='
targetRot = new Vector3(Mathf.Clamp(targetRot.x - recoilX, min, max), ...);
But you can do it on multiple lines if you want
targetRot = new Vector3(
Mathf.Clamp(targetRot.x - recoilX, min, max),
targetRot.y + Random.Range(-ry, ry),
targetRot.z + Random.Range(-rz, rz)
);
Since the new vector is not added with += make sure to do the addition in the individual vector components
Iโm new to unity and i am wondering about how i can refference a float from one script in another script.
having some issues with that unfortuneately
get a reference to the other script then access any of its public members (variables, properties, and methods) using the . operator
so I tried ```void Update()
{
//targetRot = Vector3.Lerp(targetRot, Vector3.zero, returnSpeed * Time.deltaTime);
currentRot = Vector3.Slerp(currentRot, targetRot, snappiness * Time.fixedDeltaTime);
transform.localRotation = Quaternion.Euler(currentRot);
}
public void RecoilFire()
{
targetRot = new Vector3(
Mathf.Clamp(targetRot.x - recoilX, 20, 80),
targetRot.y + Random.Range(-recoilY, recoilY),
targetRot.z + Random.Range(-recoilZ, recoilZ)
);
//targetRot += new Vector3(-recoilX, Random.Range(-recoilY, recoilY), Random.Range(-recoilZ,recoilZ));
}```
and used 20 and 80 as a min and max example
since my current clamp on my player script is 80
camera gets a bit wonky unfortuneately 
Might want to use 0 (or less) as the lower bound to Clamp. Here it says that the X rotation should be no less than 20 degrees which is not right. The default local rotation (pointing local forwards) is rotation X = 0
why are you multiplying by fixedDeltaTime inside of Update? ๐ค
guide I used did it this way 
are you sure the guide was using Update and not FixedUpdate?
nope

pain
I recognize the variable names, procedural aiming system video right?
right on the money
I used that too but saw the discrepancy and put it all in FixedUpdate
With FixedDeltaTime eveywhere
Looks like it's applying horizontal recoil fine
And rotational (around Z) too
wouldn't even need to change the deltaTime to fixedDeltaTime if everything is moved to FixedUpdate since it returns the value of fixedDeltaTime when called from FixedUpdate
your camera is rolling along with the directional shift
yep
not sure why 
Yeah it's normal, it adds a nice touch when used slightly, need to keep the values low
not sure why
Well you apply random Z rotation in the ApplyRecoil method
Actually when you need to rotate up, you subtract the X rotation, which means your clamp should be in the negative range, like (v, -90, 0)
I never remember, but in the Inspector, to look up, you input a negative X rotation right?
I did see that issue when I was debugging earlier in the day yeh
Pardon all, I have a quick beginner question:
I have a tile-based 2D game with parallax backgrounds. When I do an orthographic zoom out, everything gets smaller (as expected!)
However, I want the far background to remain the same. Is there a way to exempt any individual layer from the zoom? Or do I need to write a script that scales the background up when zooming out?
Not sure but I suppose you could have it on a canvas
Have it set to screen space overlay
It shouldn't be affected by zoom
Thank you! I'll investigate and see if that works.
private void Update()
{
transform.Translate(transform.up * moveSpeed * Time.deltaTime);
}
how do i move object up but in it's local space?
add to its localPostion
iirc
Translate operates on local space by default - use Vector3.up
yeah, the movement is already applied to the relative space of the GameObject . . .
For completness, you can pass a second argument to Translate specifying which space to apply this in
Default is local
still stumped here honestly
tried inputting other values to no avail
Is disabling the Unity splash screen in Personal version currently available in the most recent version?
If you do not apply the clamp, just rot.x - recoilX for the first arg of Vector3, is it any better?
It will be available in the next LTS (Unity 2023.x), releasing in 2024.
Not a code question, conversation should continue to #๐ปโunity-talk
recoilX - targetRot.x,
targetRot.y + Random.Range(-recoilY, recoilY),
targetRot.z + Random.Range(-recoilZ, recoilZ)
);``` like this right?
Well actually no
You swapped the two operands of the subtraction
It should be target.x - recoilX
target.x + (-recoilX) for easier visualization, like the other args
without the clamp the camera goes flying off unfortuneately again
Can you post the full updated code?
yeah np
void FixedUpdate()
{
//targetRot = Vector3.Lerp(targetRot, Vector3.zero, returnSpeed * Time.deltaTime);
currentRot = Vector3.Slerp(currentRot, targetRot, snappiness * Time.fixedDeltaTime);
transform.localRotation = Quaternion.Euler(currentRot);
}
public void RecoilFire()
{
targetRot = new Vector3(
targetRot.x - recoilX,
targetRot.y + Random.Range(-recoilY, recoilY),
targetRot.z + Random.Range(-recoilZ, recoilZ)
);
//targetRot += new Vector3(-recoilX, Random.Range(-recoilY, recoilY), Random.Range(-recoilZ,recoilZ));
}```
currently looks like this when playin
Looks normal to me
It's not returning back to the zero rotation cause the first lerp is commented out, but otherwise I don't see issues here
the camera spins around when ya keep firing
like turns upside down
would a clamp there stop that from happenin or nah 
Yeah, and a clamp won't prevent that unfortunately because the clamping should be applied to the world rotation. I guess you could make your hierarchy backwards through, the camera movement is done on the child of the object the recoil gets applied to
My code does not clamp so I think it's using that method
Or I never shot fast enough to rotate past 90ยฐ, but this gets mitigated a lot when you apply the second part of recoil, returning back to zero progressively
Im considering leavin it as is at this point cause I cant figure out how to get past this block
unity dev really beatin my ass here cause this shit haaarrrrddddddd
I think the original code would work fine for other guns but I can fine curb the shotgun by just making the spread wide
Or lower the firing rate for the recoil to have time to return back to its original rotation
oh nah I was hopin for the opposite lol
I kinda wanted it to be slower so it took longer
thanks for the help tho, I wouldve never thought to try a few of those ideas out
My system is like hybrid, it has two ways of applying recoil:
- Procedural like you have
- Following curves for finer, non-linear movement
The code is a mess though lol, I'll redo it from the ground up if I'm ever bored enough to open Unity again lol
Ive been at this recoil thing for two days when I shoudlve honestly been continuing work on my enemy ai stuff lol
my perfectionist self wanted the recoil to look like how I wanted tho so I tried in vain for these past few days
script that gets disabled doesnt run Coroutine
Most likely it really gets started at the end of the frame. Code up to the first yield gets executed immediately, but afterwards, mystery... on the c++ side
ow
public void RespawnSquare(float delay)
{
StartCoroutine(SquareSpawnManager.Instance.RespawnCoroutine(this,delay));
gameObject.SetActive(false);
}
so i can turn this into a corutine
anyone know if it is possible to get the vertices making a triangle given you have the triangle?
and add extra yield for a frame betwene?
public void RespawnSquare(float delay)
{
StartCoroutine(StartRespawningSequence(delay));
}
private IEnumerator StartRespawningSequence(float delay)
{
StartCoroutine(SquareSpawnManager.Instance.RespawnCoroutine(this, delay));
yield return new WaitForEndOfFrame();
gameObject.SetActive(false);
}
looks ugly but maybe it works
You need to start the coroutine on an active object, like
StartCoroutine(SquareSpawnManager.Instance.RespawnCoroutine(theOtherObject, delay));
theOtherObject.SetActive(false);
Now as long as the object this script is attached to stays active you're fine
but that's what im doing
No
oww yea ok
i get it
public void RespawnSquare(float delay)
{
SquareSpawnManager.Instance.StartRespawnCoroutine(this, delay);
gameObject.SetActive(false);
}
now its like that
and im starting the coroutine on SquareSpawnManager
which is a different object
Yep that works
works perfectly, tysm
how does one round that up to two decimal places
weightText.text = weight + "kg";
like this?
weightText.text = weight.ToString("F2") + "kg";
I have a "Score" script that is supposed to update the score on my TextMeshPro component, but I can't seem to get a reference to that component in the script. What component is the script supposed to be attached to?
Some of the stuff I've tried but I keep getting object reference null error
use TMP_Text rather than TextMeshPro. TextMeshPro is the non-UI text but you probably want the UI one which is TextMeshProUGUI. however they both inherit from TMP_Text so you can use that for either one with no issues
OK I'll try that thanks
i would also recommend just dragging the reference into the inspector rather than using GameObject.Find then GetComponent
Tried that too but it's not letting me for some reason
That's why I think the script is attached to the wrong component
is this script perhaps on a prefab?
this statement makes very little sense
your scripts are components
you have not switched to the correct variable type
not sure how to do that tbh
your myText variable needs to be of type TMP_Text not TextMeshPro
Text Mesh Pro is the Non-UI version of TMP
OK I did that but I still can't associate an asset to that variable, which is why I think the script is on the wrong asset (prob not the correct terminology)
is the Score component on a prefab?
no it's on a ui element
that doesn't preclude it from being a prefab. but so long as both objects are in the scene at the same time and you have the correct type for your variable then you can just drag the text object in
if it is still not working then screenshot the unity editor so that we can see both the hierarchy and the inspector while you have this object selected so we can see the Score component in the inspector
okay so if you drag either the component in or the entire Text(TMP) game object in, what happens?
it doesn't do anything
wdym it doesn't do anything? can you record what happens?
yes
this is not even the TextMeshProUGUI component.
the font is still the old Text component
oh shit, i didn't even notice that. how did that even happen
so how do i change it to the proUGUI component
remove the Text component and add the TextMeshProUGUI component
this is the add component menu
You click add component
that's the button in the inspector if you scroll all the way down. it literally says Add Component
ok found it
ok now a new error pops up
the object of type "TextMeshProUGUI" has been destroyed but you are still trying to access it
well it seems like you're trying to access something after it has been destroyed. you'll need to show the context for where this error is happening
at a complete guess though, i'd say it's either you forgot to unsubscribe from a static method when an object was destroyed/scene unloaded
is this error happening during play mode?
yes
and what happens in the scene that triggers this error?
well that means almost nothing to me without code context. i'm assuming that interacting with those pellets tries to change the text property of the TMP_Text object?
can you show the code that tries to use the TMP_Text object?
and can you also show the entire stack trace for the error
๐ Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
can i use the same velocity variable for 3 different smooth damps?
or is it gonna go weird
you're still using GameObject.Find and GetComponent so you're overwriting the myText variable in start. if you've dragged the component in, then just remove those lines since they become unnecessary
but i'd still like to see the stack trace for the error to determine if it even is related to your code
just screenshot it
okay so first, always focus on the first error in your console. that is causing the subsequent errors. so make the changes i suggested [here](#๐ปโcode-beginner message) and it should work just fine
I got rid of those lines but the errors still keep coming and the canvas part in the script went away
show the stack trace for the errors and what the code currently looks like
and the code?
myText = temp.GetComponent<TextMeshPro>();
what is this line for
its the same code i linked earlier
it shouldn't be
is that line causing issue?
myText being re-assigned TextMeshPro from temp
i got rid of that line
show the updated code
ohh maybe send the code thats up to date lol
add this line to Start: Debug.Assert(myText != null, $"myText is null on {name} {GetInstanceID()}", gameObject); and show what it prints
oh wait. your updated code is wrong. you're still using the wrong variable type for some reason
oh which one should it be
TMP_Text
hey im trying to make my character be able to move and can't find any scripts that make me able to
on 2d
no gravity also
there are plenty of tutorials you could watch for that
ok
im gonna take a break from this project i have been at it for like 4 hours
thanks for the help @slender nymph
does anyone know if there is a way to randomize the mass of an object?
generate a random number using something like Random.Range then assign it to the mass property on the rigidbody
this is a code channel. also depending on your version the navigation workflow has changed and you're clearly watching a tutorial from a really old version
I have this scene with basic stuff always existing like controls and ui but star + planets and skybox changing across star systems should I use additive scene loading for planets it must exist for a reason but idk why I shouldnt just destroy those dynamic things and rebuild in same scene lol
but, where I find this? i want create a AI for my game, Can you help me?
again, it depends on your unity version. but this is still a code channel.
#๐คโai-navigation
there's documentation pinned in that channel that you can read
help me with inventory pickup please
anyone
i cant pickup and add 5 items to inventroy
What do you have so far?
Show the code. Are you using a foreach loop when picking up weapons?
So I am using raycast
// ray from the camera
if (Physics.Raycast(ray, out hit))
{
hitObject = hit.transform;
float distance = hit.distance;
if(distance < 9 && hitObject.tag == "Weapon" || hitObject.tag == "Item")
{
showLabel = true; // SHOW THE PICKUP LABEL
// PICKUP THE GUN
if (Input.GetKeyDown(KeyCode.E))
{
if (weaponAmount > 0)
{
Debug.Log("altease one weapon in hand");
SwitchWeapon(hitObject);
}
Debug.Log("weapon pickup first " + hitObject.name);
Transform transforms = GameObject.Find("gunContainer").transform;
if(!weapons.Contains(hitObject))
{
PickUP(hitObject.transform);
}
}
}
else
{
showLabel = false; // SHOW THE PICKUP LABEL
}
}
if(!equipped && Input.GetKeyDown(KeyCode.G))
{
equipped = true;
}
// DROP THE GUN
if (equipped && Input.GetKeyDown(KeyCode.G))
{
equipped = false;
Transform game = GameObject.Find("gunContainer").transform;
DropGun(weapons.ElementAt(weaponAmount));
}
@summer stump
So the error mentions "MoveNextRare"
What is that code?
if i were to make a script to store values, should i leave it as monobehaviour or change it?
Should it be a component or not?
yeah
If it needs to be a component, then use MonoBehaviour
The script must inherit from that (or Component or Behaviour, but keep it simple and use MonoBehaviour) to be a component of an GameObject
That's a lotta nesting. 
Can u even inherit from Component or Behaviour? (Ik u can because they're public but it seems unusable anyways even if you can.)
I have NEVER tried. So i don't know haha
Yeah i tried, it asks for an attribute that you can't even use.
I just felt like someone would point it out, so I was covering my a

Good to know. Thanks for testing hah
I spend too much time on reddit lol
What is the easiest way to detect how a button is pressed (GUI)?
wdym how?
Add a listener to it. If code isn't natural to you though, you can add a function to the button triggers in the inspector
I am having trouble organizing an algorithm I want to build. I have a list of characters in a row and I want them to switch their order in the scene based on the current active character, so if the index is 1, I want character A to be first, character B to be 2nd, etc. And if the index is 4, I want character D to be first, and then A to be 2nd. I just have to set the sibling index of the characters to get the display to work right, but I have no idea how to do the math within the for loop to make it work for any length of Active Players. Any ideas?
// handle the display order
// if we have a list of 4, and the current index is 3, then the 3rd one is 1st, the 4th one is 2nd, the 1st one is 3rd, and the 2nd one is 4th
// 1 = 3rd
// 2 = 4th
// 3 = 1st
// 4 = 2nd
for (int i = 0; i < ActivePlayers.Count; i++)
{
ActivePlayers[i].transform.SetSiblingIndex( ??? );
}
can anyone help me with my vs code intellesence
i regenerate my project files and reloaded window
and got an error message
RemoteInvocationException: Sequence contains no elements
bro we in that channel ๐
Nah its reference to a message
oh lmao its a message reference
If you click it it will take you to the message
I thought bro mentioned the channel ๐
Same for me at the start
believe me it confused me to. I looked up my old message and copied message link, and hit paste and thats what it came up with, but it worked lol
Mhm
discord is getting a lot cooler with its references
But there is many videos about how to get intellisense working in vs code
Indeed unlike Unityโs pricing plans ๐
๐
real
alt + right arrow key expands it for me, might work for you too (alt + left to close it)
Weird question but
Is it possible to add a type to a variable?
Like var i = int or something like that
I have this gigantic function https://pastebin.com/gj85Lm5L
And it is already complicated enough
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
I still need to repeat it for the land tiles
Would be easier to just change the type on tilemap.GetTile<T> instead of repeating everything again
Is that possible?
There's the Type type(no pun intended). That you can use to store a type in a variable.
Though, perhaps you're doing somehting wrong if you need to rely on it.
You can't use it with generics though, if that's what you plan.
Oh
Yeah that's rough
Can I use something like tilemap.GetTile<typeof(tile)>
And tilecan be my two different types of tile?
No, I don't think you can do that. I think generics are evaluated at compile time, when tile is undefined.
Perhaps you can use polymorphism to solve your issue. Not entirely sure what you're trying to do though.
I'm using it to check types of neighbors
It gives me inconsistent results if I use GetTile returning TileBase
You can just check the type of TileBase
For example, if I use is operator to check the type, it is always returning false
if(tile is WaterTile water)
{
//do something with water tile
}
else//...
When I use Equals, i get a null reference too for some reason lol
I tried, it always gives me false
I don't see how Equals is relevant here, but is should work
Can you provide the code and some info on the tiles?
Sure
WaterTile: https://pastebin.com/SqQPXJ12
LandTile: https://pastebin.com/kGpDMTCD
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.
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.
Maybe I was just doing something wrong
When comparing
I remember I may have had cast the tile before comparing
I'll try again
Thanks for the help tho
Yeah, try the is again and see if it works.
Tbf, just using type checking would accomplish the same thing I'm doing rn, same lenght
As I'm checking type already, just differently
I guess so
So yeah, thanks for the help anyway
Would be nice to have a way to change the type of a generic in runtime
You can use polymorphism perhaps:
MyTileBase t = GetTile<MyTileBase>(pos);
t.DoSomeSpecificLogic();
And then override the DoSomeSpecificLogic in each of your types inheriting from MyTileBase.
Or something more intricate, depending on your needs.
The game of life?
Sorry?
Sorry I thought your code looked similar to John Conway's game of life
Loops and checking neighbors are very common in different algorithms.
It may have similarities
I was trying to do a flood fill algorithm without it being a flood fill algorithm
That's why it isn't the best code out there :p
I don't know what your end task is but if it has anything to do with changing tiles to a different 'tiletype' depending on what the neighbors are, then you will most likely need a "currentState" of the tiles and "nextState" of the tiles.
You don't want to change them as your doing your for loop
Oh, it's not continuous. it's just one step on the island generation to clean up single out tiles.
So I don't get a random single water tile inside the island
So Iโm making a card game, where up to 5 hands are in play (5 cards per hand). The last card is face up and the person with the highest card will be the leader for the round.
However, if multiple people share the highest card I donโt know how to handle the situation.
So far Iโve just stored all the 5th cards in a List<GameObject>.
here's my island
Do you want more than 1 leader when it's a tie?
Care to detail more your problem?
Is it a question about game design or coding? Are you asking about what to do when there's a tie or how to code it?
How to code it. I want only 1 leader, and when there are multiple people with the same highest cards I want to deal another card to only those hands and check again if one has a higher card.
So, only one person can have the highest card and when they pick it, no one else can?
Is that what you want?
So potentially, but very low probability, having the same highest card can happen several times
They donโt pick it, but the final card dealt to their hand (which is face up) decides their โleader valueโ. Highest leader value gets to be leader for the round, but only one can be leader per round
How can i call the GameObject OnMouseEnter from an array of GameObjects?
[SerializeField] private GameObject[] gameObjects;
private void Start()
{
foreach(var gameObject in gameObjects)
{
//Subscribe to OnMouseDown / OnMouseEnter?
}
}
private void OnMouseDown()
{
}
private void OnMouseEnter()
{
}
Ok, so just set a bool to true when someone gets that card and when giving cards to other players, exclude that one card from the options.
foreach (object in gameObjects) { object.OnMouseEnter }
Tho I suspect you wouldn't need to do that if this is an event
Sadly i tried to do this earlier and didnt work:
actually you should get component first
but i will not suggest this, instead change the gameobject[] to some monobehaviour[]
That's not how you should be subscribing events
You are subscribing the function... to itself?
But I cannot know for a fact its the highest card until all cards are dealt out.
Well im kind of puzzled.. All I want to to do is handle the OnMouseEnter of gameobjects inside of 1 script instead of having like 100 scripts.
When I make a single script to do it for each object, it works very well
This is interesting ๐ฎ
So, that's how events are for, but you are doind it wrong
Lemme see if I can find a tutorial
For events
yeah i feel like it hehehe
Good resource about events
Awesome, thank you so much ๐
Then you have a problem and you need to decide how to deal with it from the game design perspective. Do you do 2 card draws(one to know the leader and then another to make sure no one has the same card)? Maybe some other logic?
Also, I'm pretty sure you can use built in Unity functions for that? Just make a ray coming out of the mouse, and let the ray script handle what to do when the mouse enters, not each object
you should look up the method you're trying to use to see how to use it . . .
No i only deal the 5 cards to each hand and then do the leader check. And when we play the card game irl sometimes 2 people get the same leader card more than 2 times in a row, so it needs to be able to re deal until thereโs a leader
Oh, I didn't know OnMouseEnter was a Unity event
Like, a built in function lol
Ok, so when you redeal the cards, just exclude any cards that are the leader or higher cards from the distribution.
foreach (var item in colliders) Destroy(item);
var actualWidth = pixelSize * size.x;
var actualHeight = pixelSize * size.y;
var actualHalfSize = new Vector2(actualWidth, actualHeight) / 2;
foreach (var rect in PDCG.GenerateColliders(pixels, size.x, size.y))
{
var box = gameObject.AddComponent<BoxCollider2D>();
box.size = new Vector2(rect.size.x, rect.size.y) * pixelSize;
box.offset = rect.center * pixelSize - actualHalfSize;
}```
why does this only work the first time
this sounds like a custom solution you need to build. by default, each GameObject will react independently if using OnMouseDown method from MonoBehaviour. you can also use pointer events to use OnMouseEnter . . .
after its used for the first time, whenever I use it afterwards, it only deletes the colliders but doesn't generate new colliders?
for example here is an object
you add multiple boxcolliders to same gameobject?
yes
if it doesnt create new collider on the object, the foreach loop is not execute so PDCG.XXXX iterate nothing and yield return nothing
while (transform.childCount > 0)
DestroyImmediate(transform.GetChild(0).gameObject);```
why would this cause infinite loop
doesnt make sense to me
Afaik, it shouldn't. But it does seem like a very bad way to destroy all the children
Use a reverse for loop
Also, 2 lines of code doesn't really show much lol, show everything of the while loop
Oh, it's only one line
@versed light (missed how long ago you posted, have a ping)
yeh doing it in reverse worked - would've thought destroy immediate did it instantly though
maybe it acts different in edit mode
I have a question about tilemap.RefreshAllTiles. Does it call the RefreshTile of each tile?
press f12 on the function and take a look at the code for it
unless they made it external
I'm having some weird behaviour when calling it
(f12 for visual studio) might be a different key if you use a different ide
Thanks, I'll try that
But I guess my problem is with tiles being scriptable objects (I'm passing a value to a custom tile class)
Hmm I'll see what I can do
ye, the tiles were getting the last value set, all of them
So I actually need to not refresh my tiles
Hoi. Is the Space/Enter button considered in unity with some sort of "pressing" function? I mean like when you use Tab button in the browser to select a button and pressing enter will press that button like you clicked on it. I hope it's clear what i mean.
I noticed in my game if i open my inventory and there is a button to drop stuff, when i click on it and press space or enter the button still gets "clicked". If i just open the inventory and press space/enter nothing happens just after 1 click registered (with mouse) for that button.
Im pretty sure its some kind of wierd button mechanism because if i click once more anywhere and then try to press space/enter it no longer registering as i trying to press it.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class PlayerData
{
public int shardTotal;
public bool is_tutorial_done;
public struct Level
{
public int shards;
public float finishTime;
public bool is_level_done;
}
public Level[] lvl = new Level[10];
public PlayerData()
{
}
}```
how do I initialize the struct (lvl) in the constructor instead? (if that's even possible) because when I do it throws me the null reference exception
you mean lvl[some index].something gives you an NRE?
This code works fine. I simply put in the reference gameobject for the SwitchUnit in the inspector.
But what if I want SwitchUnit to be more than 1 object?
Maybe objects that has a certain tag or rather any gameobject that is specifically in that position in the if statement?
What do I write?
in playerdata yeah
How do I define SwitchUnit then?
even if I create a new PlayerData object in another script and try to initialize any lvl I get NRE
only way it works is w the syntax I put above
i think it is impossible to throw NRE in your case.. maybe try lev=new Level[10] in the constructor first
level is struct
You have to initialize the array before you access/set its members, not doing that is the only way you would get an NRE
yeah that's what happens I assume
ah it's cuz I Load first and save later, so they never get initialized unless I save the game, so I try to load nothing
Hi - if I had an object I wanted to rotate around another object, to point at a third object...
o
. x z
So rotate o around x (to .) to point line up with z - any smart ways?
I know I can rotatearound x, but I'm not sure of the cleanest way to figure out the angle, or indeed if tehre's a shortcut
Does anybody know why this (C#) code isn't working? It doesn't give me an error, it just doesn't do anything. I have the event triggers set up and everyting.
Looks fine, though your event trigger concerns me, what object is that on?
Also, you need to configure VS
!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)
The script is on the canvas
But it is doing that
It needs to be on an object like a Graphic or Collider. You cannot get UGUI events without an appropriate thing for the event system to click
What exactly do you mean by that? I added the event trigger to the button that should make the settings show up and the code to the canvas like a tutorial I watched a while ago for a tab system did and the tab system works perfectly fine
Events are sent using various scripts, the one on the canvas is called the Graphic Raycaster
it looks at Graphics under the canvas and sends events if they were relevant
Events are only sent to the gameobjects that have the Graphic (like an Image) component on them. If you have a Canvas object alone, there is no event sent
You also need an Event System in your scene, in case you got rid of it by accident
An object named "Event System" in your hierarchy
On the canvas I have both the object that one should trigger the event and that should be triggered by the event and both of them have a sprite renderer
I've done that before and spent about 1/2 an hour trying to find the mistake, but now it is there
A Sprite Renderer is not a Graphic
what kind of graphic shoud I add then bc I dont want to affect the look of the sprite
Image is the component you use inside of a Canvas
Can I then just make the A-Value of the image 0, so it is invisble?
Edit: Yes, you can
like that
Now it works, tysm! Didnt know that needs an image compenent
Or just give it a collider2d
the button had that
Something that's able to get bounds check
Maybe you did not have a physics 2d raycaster for the camera?
The canvas has one
That's correct, it does not need to be anywhere else but on canvases and subcanvases
If it's working, there's nothing more to worry about
Will methods in Debug be built into my packed game, and cause unnecessarily performance overhead?
Logs yes, asserts no. Logging in builds can be switched off in player settings.
ok, thanks!
im making a vr shooter and i have 1 problem, im using a bullet model (not a spheare) and my bullet flys facing one directions, its shoots in the right direction but doesn't face the right direction, lets say i turn 90 degrees my bullet i just shot will be flying at 90 degrees which looks goofy, i dont know how to fix this and i dont want to make the bullet a sphear and ignore it.
this is my code
assign its transform.forward to the spawnPoint.forward since that is the direction it is being fired in
alternatively you can pass in the spawnPoint.position and spawnPoint.rotation to Instantiate and you won't have to manually assign those on the following lines
how do i do that ;-;? im really new so all my code is from tutorials
assign its transform.forward to the spawnPoint.forward
is literally how
i'm not going to write the code for that for you
okay okay, thanks tho
and if you read the second message i sent, you'll see an even easier way
In the editor:
https://docs.unity3d.com/ScriptReference/EditorGUIUtility-systemCopyBuffer.html
But there's no built-in equivalent for runtime. There are plugins that exist that implement it for some platforms. Each platform handles the clipboard differently.
hmm i need a runtime thingy ๐ฅน
So I have a list full of scriptable objects and I was wondering if you can get one scriptable object with just the name of that scriptable object for ex I have a scriptable object named Tom so I would search for Tom in my list
Use a dictionary lookup system?
I got a pickup and drop system but every time I drop the weapon the weapon is droped at the origin of the scene instead being droped at the current location. The only thing i'm doing in the script is unparenting the weapon from the character and disabling some scripts. help pls :(.
Does the weapon have an animator? If yes, try disbabling it before unparenting.
It might be overriding the guns local position to 0,0,0
And with no parent that becomes the world position
That or the rb might remember its last non kinematic position.
Serialize structs, yes. Arrays, depends on the serializer
JsonUtility cannot serialize arrays directly, you have to wrap the array in a class and serieliez the class
will i get problems if i load this from json?
well that explains my issue
ooh another json pwoblem
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class PlayerData
{
public int shardTotal;
public bool is_tutorial_done;
public struct Level
{
public int shards;
public float finishTime;
public bool is_level_done;
}
public Level[] lvl = new Level[10];
public PlayerData()
{
}
}
I'm trying to serialize this
Not sure why you write instance IDs, given that they change between game runs and object instances
i just used this JsonUtility.ToJson(MainCharacterController.mainCharacter);
Well it's trying to serialize some components there, not sure what the behavior will be on deserialization
same here, and I get this error when I try to use FromJson
Error occured when trying to read data from a fileC:/Users/Rob/AppData/LocalLow/myDevStudio/LIMBO RGB\data.limbo
System.ArgumentException: JSON parse error: Invalid value.
at (wrapper managed-to-native) UnityEngine.JsonUtility.FromJsonInternal(string,object,System.Type)
at UnityEngine.JsonUtility.FromJson (System.String json, System.Type type) [0x0005c] in <7fe3f96a6d704e1eaaf6ef514c2f5a51>:0
at UnityEngine.JsonUtility.FromJson[T] (System.String json) [0x00001] in <7fe3f96a6d704e1eaaf6ef514c2f5a51>:0
at FileDataHandler.Load () [0x00031] in D:\Unity Projects\LIMBO RGB\Assets\Scripts\DataPersistance\FileDataHandler.cs:34
UnityEngine.Debug:LogError (object)
Fields referencing components should probably be ignored
By decorating them with the NonSerialized attribute, probably
Mark the struct as serializable.
If the struct is meant to be used outside of PlayerData, consider taking it out of the class, and moving it to its own file.
im still stuck on how to do this, tried googling how to assign them together. "+" gives me an error if i do spawnPoint.position + spawnPoint.rotation;
I guess they mean spawnedBullet.transform.forward = spawnPoint.forward.
Or doing = Instantiate(bullet, spawnPoint.position, spawnPoint.rotation), you choose
Both will rotate the instantiated prefab accordingly, so it faces the same way as the spawn point
If you choose the second approach, you won't need line 27 also
thank you, the problem is when asking for help is that i dont know how to code, so all the terminology is alien to me, ive just been learning how to do what ive seen but when something new pops up im clueless
What is the problem Ryldex
Configuring your code editor should be a first, if you haven't done that yet. You'll get errors underlined red in the code directly, as well as suggestions when you type stuff (variable names, type names, etc.)
your trying to add a quaternion (spawnpoint.rotation) with a vector3 (spawnpoint.position)?
!vscode
Do you really think this is enough info to help you
i got that error when i put in the cod e yo sent
