#💻┃code-beginner
1 messages · Page 32 of 1
can you screenshot the inspector of the gameobject
Ah, right, you have a Rigidbody attached. instead of setting transform.position in your script use rigidbody.position @thick goblet
after the value is set, yes . . .
rule of thumb, never mix transform and rigidbody movement
rb.MovePosition to keep interpolation
Nvm you probably dont want that here if it is supposed to teleport
Yeah it works perfectly now
I'm probably just dumb but why doesn't this work?
Ah thanks I get it, I'm missing the quaternion rotation
should the items know which slots there in?
if yes i can do it simply
the durability
Whats the slots got to do with durability?
Is it that only items in a slot will decay?
like when i shoot i can just item.cell.RefreshDurability();
update the cell the item is in
same for food
Ok so it is just for UI?
A clean way would be to use events or something
thats what im doing
Make the UI system listen to an durability change event
vector3 is not a transform.
Correct. There are a few different overloads for the Instantiate method
Same method name, different arguments.
None of them take only a position
You'll want either Quaternion.identity for a "default" rotation, or enemyType.transform.rotation if you actually want to preserve the prefab's rotation
Het I'm trying to rotate a head along the Z axis. In the Scene editor it automatically adjusts for the position aswell. How do I do this in code when I just try to edit the Z rotation it goes around the player body.
This is the current code I use for rotating the head.
y = Input.GetAxis("Mouse Y");
Vector3 headCenter = bodyHead.transform.position + bodyHead.transform.up * radius;
bodyHead.transform.rotation = Quaternion.Euler(bodyHead.transform.eulerAngles.x, bodyHead.transform.eulerAngles.y, bodyHead.transform.eulerAngles.z + y * sensitivity);
In your editor you have your tool handle pivot set to "Center"
set it to pivot and you'll get the same behavior as the code when rotating
Also there's a much better way to do the rotation:
Quaternion rotation = Quaternion.Euler(0, 0, y * sensitivity);
bodyHead.transform.rotation *= rotation;```
If you want the code to rotate around a certain point you need to either:
- adjust the mesh in blender to have its pivot in the correct place
- introduce an empty parent object to the head with the expected pivot and rotate that parent object instead of the head itself
How do you set the pivot of that empty object? I already have an object in which the sphere and eyes are located but now I see in the editor that that's at the same position as the bottom of the body.
hi, i have this problem with player animations in unity. heres a video of what happens when the player should stop as i let go of all the keys( https://youtu.be/DNTlrbIxQNE) there's some sort of a delay before changing isMoving to false
also here's the HandleUpdate function
public void HandleUpdate()
`{
if (Input.GetAxis("Horizontal") != 0f || Input.GetAxis("Vertical") != 0f)
{
animator.SetBool("isMoving", true);
animator.SetFloat("moveX", Input.GetAxis("Horizontal"));
animator.SetFloat("moveY", Input.GetAxis("Vertical"));
}
else
{
animator.SetBool("isMoving", false);
}
if (isMoving) // Sprawdź, czy ruch jest włączony
{
movementDirection = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
}
else
{
// Zatrzymaj animację ruchu, gdy ruch jest wyłączony
animator.SetBool("isMoving", false);
}
}`
Input axes have an interpolation of the value from 1/-1 to 0. It's not immediate. That's the whole point of the input axes.
the empty object's pivot is just its position
like I said before you need to set your tool handle position to Pivot, not Center to see it properly
Press Z to toggle it
oh I got it thanks alot
my project has got stuck at one point as when i am taking reference from the one script to another it is not sowing any changes in the 2nd script when something is getting changed in the 1st one
you need to share details
such as code and how things are set up in the scene
and what you are doing and expecting to happen, and what is happening instead
Wanted to spawn an enemy either in pairs or four in a square. This works but I'm sure it's spaghetti.
Show code
Hey guys, i'm trying to add bullet spread to my 2D top down shooter. however, the bullet keeps coming out at very peculiar angles when i shoot the gun. in the code below, which is the part that needs fixing, FirePoint is the point from which the bullet appears, and also is facing in the direction that the bullet needs to be fired in. can someone tell me whats wrong?
Vector3 BulletDirection = FirePoint.rotation.eulerAngles;
if (Input.GetKey(KeyCode.Mouse1))
{
BulletDirection.z += Random.Range(-bulletSpreadADS, bulletSpreadADS);
}
else
{
BulletDirection.z += Random.Range(-bulletSpreadHipFire, bulletSpreadHipFire);
}
FirePoint.rotation = Quaternion.Euler(BulletDirection);
GameObject bullet = Instantiate(bulletPrefab, FirePoint.position, FirePoint.rotation);
Rigidbody2D rb2d = bullet.GetComponent<Rigidbody2D>();
rb2d.AddForce(FirePoint.up * bulletForce, ForceMode2D.Impulse);
So, I think the problem here comes from the fact that each time you fire you are permanently rotating your fire point, meaning the randomness of the rotation can compound infinitely in either direction depending on how the numbers go. You get the current rotation, modify an angle, then put it back, meaning next time it'll have the new adjusted values before rolling again
oh damn you right
Add on to the fact that getting the eulerAngles does not necessarily mean you'll get back the same vector you put in, the Z is not always going to be the same. If there's a "better" way to represent that orientation with values on X and Y with a 0 Z angle, it will
It's probably better to get the up direction of the FirePoint, then multiply that by a Quaternion.AngleAxis rotation about the Z-axis by some random amount of degress, and that'll get you a resulting rotation that applies that rotation to the FirePoint's up direction. Use that for your bullet's rotation and velocity instead.
https://docs.unity3d.com/ScriptReference/Quaternion.AngleAxis.html
directly manipulating euler angles is rarely a good idea
could you tell me how to write this as code please? im quite new to unity and im still grappling with all the ideas of vectors
you can multiply a quaternion with a vector to rotate the vector.
Quaternion.AngleAxis(45, Vector3.forward) is a rotation by 45 degrees around the Z axis.
I asked in unity talk but I think it fits way better here now that I think about it. Is there a variable type to store a function?
yes, those are what we'd call "delegate" types
System.Action can hold a function that takes no arguments and returns nothing
System.Func<T> holds a function that takes no arguments and returns T
any void function?
Both can have extra generic type parameters added to represent functions that take arguments
With zero arguments.
System.Action<int, float> is a function that takes an int and a float and returns void
only?
use of gameObject in MonoBehaviour script leads to NullReferenceException
great to know thank you
also can I make it choose a function from the editor?
I was thinking maybe a way around was making a string and writing the name of the function for each gameobject
string();
could I do that?
I was afraid of that
That would work with something like Invoke, which tries to call a method on a component by name
i would suggest using UnityEvent if you can
never used it before so I would need to make a little bit of research
it's what Button uses
ohhhhhhhhh
that makes sense
I was trynna get something close to animation events
It lets you assign references to any unity object and pick a method to call
are there any downsides to that?
compared to calling it directly in the script
The methods you invoke with a UnityEvent can't return values. They have to return void.
The added complexity of having to assign it in the inspector and thus adding a "second place" you have to check to get the full grasp of what a script can do
It can't be statically analyzed
But you gain in modularity being able to use the same code to do different things
You can ask your IDE "where does this function get used?"
but it will have no clue about UnityEvents
because nowhere in your source code is that method called
yah thats what I was trynna do
basically I have enemies and an enemy script
and I wanted some of them
to have special effects
so I was going to do it like that
UnityEvent is a good fit for "when X, do Y"
pretty simple effects so I would only need to call a void
this sounds like such a situation
you don't "call a void"
you call a method that returns void
how is this code? it says i cannot multiply Vector3 by Quaternion but im sure that is an easy fix, so do I have the right idea you were going for or am i doing it all wrong?
void shoot()
{
float randomAngle;
if (Input.GetKey(KeyCode.Mouse1))
{
randomAngle = Random.Range(-bulletSpreadADS, bulletSpreadADS);
}
else
{
randomAngle = Random.Range(-bulletSpreadHipFire, bulletSpreadHipFire);
}
Vector3 bulletOrigin = FirePoint.position;
Vector3 bulletRotation = FirePoint.up * Quaternion.AngleAxis(randomAngle, Vector3.up);
GameObject bullet = Instantiate(bulletPrefab, FirePoint.position, Quaternion.Euler(bulletRotation));
Rigidbody2D rb2d = bullet.GetComponent<Rigidbody2D>();
rb2d.AddForce(FirePoint.up * bulletForce, ForceMode2D.Impulse);
}
}
You can pass several arguments with UnityEvent
Wrong order.
ok thank you thats good to know
Quaternion times Vector3
can I pass none also?
Quaternion times vector, not vector times quaternion. When you're in four dimensions, order matters
Yes.
ok that sounds amazing
Quaterion.AngleAxis(45, Vector3.forward) will rotate whatever you multiply it with by 45 degrees around the Z axis
the Z axis points into the screen in a 2D game, generally
so, suppose you replaced 45 with a random angle...
Also you want to rotate about the Z axis, so it'd be Vector3.forward
using Vector3.up would rotate your vector around the up-down axis, which would spin it out of the 2D plane entirely
you'd be shooting at the player :p
ok it works, the bullet sprite goes the correct direction, but the bullet is flying sideways, how do i make the bullet sprite change direction
Does anyone have a tutorial about monopoly in unity?
as in the sprite is rendered facing the wrong way
youtube it
its not gonna easy as beginner though
Ok
Set the bullet's transform.up to the direction it's moving in
I have made a prefab as PowerCellCollectible. Shouldn't 1, 2, 3, 4 be child element?
how do i do that??
With =
why would they
Why would they
so i just do bullet.transform.up = bulletRotation?
I am wanting to add a box collider but I am thinking that if I add it to powerCellCollectible then I will not have to do it for the rest
Exactly
as long as you apply the changes to the prefab it wil propagate for all
I am not sure if I have made a prefab
now all the bullets are invisible, im assuming that im rotating them around the wrong axis or smth
if its blue its a prefab, yours looks like a prefab variant
Possible. Try debug logging the direction when you fire
here is the code i changed since i last posted the whole thing here:
GameObject bullet = Instantiate(bulletPrefab, bulletOrigin, Quaternion.Euler(bulletRotation));
bullet.transform.up = bulletRotation;
Debug.Log(bulletRotation);
That rotation you created on line 1 is nonsense
bulletRotation is a direction
Just use Quaternion.identity to give the bullet no starting rotation
I dont need to add a listener if my unityevent is serializeField right?
you add listeners through code if you want to add listeners...through code
You don't have to do anything for the ones you added in the inspector
ok I was just wondering that
i figured since im so bad at this ill just send the whole function again so people can see better what ive done wrong haha
void shoot()
{
float randomAngle;
if (Input.GetKey(KeyCode.Mouse1))
{
randomAngle = Random.Range(-bulletSpreadADS, bulletSpreadADS);
}
else
{
randomAngle = Random.Range(-bulletSpreadHipFire, bulletSpreadHipFire);
}
Vector3 bulletOrigin = FirePoint.position;
Vector3 bulletRotation = Quaternion.AngleAxis(randomAngle, Vector3.up) * Vector3.forward;
GameObject bullet = Instantiate(bulletPrefab, bulletOrigin, Quaternion.Euler(bulletRotation));
bullet.transform.up = bulletRotation;
Debug.Log(bulletRotation);
Rigidbody2D rb2d = bullet.GetComponent<Rigidbody2D>();
rb2d.AddForce(FirePoint.up * bulletForce, ForceMode2D.Impulse);
}
replace Quaternion.Euler(bulletRotation) with Quaternion.identity.
You are trying to interpret a direction as euler angles
surely that will remove the random aspect of the shooting?
No. That's what the next line does.
I noticed that you aren't using bulletRotation when adding force
This will make every bullet fly in the same direction.
hang on, things are mixed up here
I see why it's partially wrong.
Is there a difference?
okay yeah that's all wacky
Vector3 bulletRotation = Quaternion.AngleAxis(randomAngle, Vector3.up) * Vector3.forward;
This is wrong for two reasons.
One: you are using Vector3.up as the rotation axis. This is spinning around the up-down axis. That is wrong.
yes I sent docs explaining the differences
You need rotate around the Vector3.forward axis.
Two: You are multiplying this rotation by Vector3.forward
This is applying a random rotation to a vector pointing out of the screen
I don't think you wanted to do that.
I think you wanted to do this:
Vector3 bulletDir = Quaternion.AngleAxis(randomAngle, Vector3.forward) * FirePoint.up;
This will randomly rotate the fire point's up direction
The rotation will spin it around the Z axis
ok i have changed all of the things you said
you can now use this direction to:
- set
transform.upon the bullet - add force to the bullet
i believe its working but instead of changing the directions that the bullets fly it changes the rotation of each bullet
Yes, because you also need to use this vector when adding force
Currently, your force is not random.
you'll always fire in the direction of FirePoint.up
so i should do rb2d.AddForce(bulletRotation * bulletForce, ForceMode2D.Impulse); instead?
Correct.
bulletRotation is a bad name, by the way
It sounds like it should be a rotation value
It's not. It's a direction.
bulletDirection or bulletDir would be appropriate
ok i changed it i see why its confusing
It's important to make it clear how to interpret a Vector3
- as a position
- as a vector (whose length matters)
- as a direction (whose length doesn't matter)
- as euler angles
- as a velocity
- ...
yes i think i need to do a bit more research on them ha
im very clueless
anyways it works now thanks bro
Cursed applications for Vector3:
- Health, Mana, Stamina
- Hips, waist, bust
- Three unrelated numbers you kinda wanna group for whatever reason
- Scientific notation whole part, decimal part, power of 10
How about instead of null we have a Vector0
public float Vec1(float t)
{
t *= scale;
return noise.snoise(xVec * t + xOffset);
}
public Vector2 Vec2(float t)
{
t *= scale;
return new Vector2(
noise.snoise(xVec * t + xOffset),
noise.snoise(yVec * t + yOffset)
);
}
unit type! unit type!
a zero-tuple is indeed a valid way to represent a type that only has one value
i have no idea what is happening anymore but i love it
wait until you find out about the bottom type
˔
oh my god the tack is so small in discord
it's supposed to look like this
damn
the bottom type has zero values, and is a subtype of every other type
so whats the point of it then
it's the return type of a method that never returns in some languages
you can never get it, so the method must never return, by definition
never in typescript, for example
C# lacks such a type
(this is very esoteric)
confusingly, it's sometimes called the "void type", but this is different from C#'s void
void is very strange when you think about it. It's a type, but it has zero values, but it can still be returned
i think thats enough C# for one day
hey idk if this is the right place to ask but i put "play automatically" off on my animation but it still plays automatically, how can i fix that?
its not
then where do i ask?
Vector 3 for health 
gonna need a vec30 when im done with my character class
you havent declared what animator is anywhere
That's not what I asked, you're trying to pass in a "PushButton" true
btw what is animator
a myth
public int animator?
🧑🏫 Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/
you need to first declare a variable then use it
go back to your tutorial and copy the code more closely.
if you're not using a tutorial, you should be
!code
📃 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.
you are trying to run a race. But you haven't even learned to walk yet
you need to learn the basics of programming first
Hi again all, can someone please point me in the right direction as to what I'm doing wrong? This is really driving me nuts now.
Essentially I'm trying to make a suspension arm point at the height of the wheel. It works to an extent (the arm does rotate, but nowhere near enough). 😕
using UnityEngine;
public class SuspensionLookAt : MonoBehaviour
{
[SerializeField] Transform wheelTarget;
//Vector3 targetPosition;
//float offset = 0.6523004f;
// Update is called once per frame
void FixedUpdate()
{
Vector3 targetDir = wheelTarget.position - transform.position;
float angle = Vector3.Angle(targetDir, transform.forward);
Debug.Log(angle);
Vector3 newRotation = new Vector3(angle, 0, 0);
transform.rotation = Quaternion.Euler(newRotation);
//targetPosition = new Vector3(0, wheelTarget.position.y, 0);
//transform.LookAt(targetPosition);
}
}
I don't know why but I have such a weird blindspot when it comes to rotations 😕
!learn
🧑🏫 Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/
also think this is a good combo
combines some c# in Unity context
https://learn.unity.com/project/beginner-gameplay-scripting
wit this one
I want my vehicle to move in the right direction when I click D until it reaches it's current position including +3 in the x position added on, then I want it to freeze and ofcourse only move once I click D again. However, my vehicle never stops at the position I want it to and it just keeps moving right. What is the problem? https://hatebin.com/bnqgyuhlzu
do you ever set movespeed to 0 ?
Oh..
but you wont do it overnight
nah
It doesn't change anything
I think is , you're constantly adding to the nextPos so you never reach it
Oh since its in the update?
I also said debug that function, like put a Debug.Log inside
yeah well its not behind any if conditions so keeps adding onto it from your current pos,
your character is chasing a carrot on a stick
folly of human is laziness
Hi. Is there something like classes which some scripts can inherit from but that can stack up please? Like be able to set more than one thing there so one script also cointains something from another script
you need interfaces
it doesn't "inherit " though
that's the problem
because I need to run code on a specific script. Like, it is a script that gets the marked variables of "this" script and does something with them. The problem is that all the logic is using the "this" reference
public class Enemey : Entity , IShootable, Iinteractble, ILoad etc
If you want to inhert then just make a middle class inheriting from MonoBehaviour (WeaponsHolder) and inherit from that instead
Otherwise just use interfaces
just be careful with inhertence though, it just ends up a dead end street or more mess than needs to be (sometimes)
Make WeaponsHolder extend MonoBehaviour and just inherit from WeaponsHolder
that was just an example, the thing is that I need both the WeaponsHolder and another class called VariableManipulator in the same script
Then you cannot
Unless one of them is a parent class of the other, or an interface
that's why I was wondering if there was something that can inherit more than one thing
Chained inheritance is possible. Multiple inheritance is not
oh ok
Interfaces are the only way around that
Which is not really inheritance the same way of course. More of a promise of implementation
well lemme try one thing rq. Edit: nvm doesn't work haha, thanks tho, I will have to try those solutions
Wait, so what's the issue with using interfaces anyways
Provide some more info on what you're trying to do
anyone know why this isnt working its meant to let me eat objects if i am bigger then them
using UnityEngine;
public class EatObjects : MonoBehaviour
{
void OnTriggerEnter(Collider other)
{
// Check if the GameObject has collided with another GameObject
if (other.CompareTag("Car") || other.CompareTag("Obstacle"))
{
// Get the size of the current GameObject and the other GameObject
float mySize = transform.localScale.magnitude;
float otherSize = other.transform.localScale.magnitude;
// Check if the current GameObject is bigger than the other GameObject
if (mySize > otherSize)
{
Debug.Log("I ate the other GameObject!");
// "Eat" the other GameObject (destroy it)
Destroy(other.gameObject);
// Increase the size of the current GameObject (optional)
transform.localScale += Vector3.one * 0.1f; // Increase the scale by 0.1 units
}
}
}
}
it also only works if they have the tag Car or Obstacle
Add more logs and check where the code is getting up to
for example is OnTriggerEnter itself even running?
"doesn't work" is quite vague
gpt code
you put the tags to be only condition
it also only works if they have the tag Car or Obstacle
literally checking only if its car/obs
The Three Commandments of OnTriggerEnter:
- Thou Shalt have a 3D Collider on each object
- Thou Shalt tick
isTriggeron at least one of them - Thou Shalt have a 3D Rigidbody on at least one of them
if (mySize > otherSize)
Like, with interfaces I couldn't access the methods inside it because they were already like defined
nope
Actually interfaces are the opposite. You can't define them in the interface, you have to implement them on the scripts that use it
using UnityEngine;
public class EatObjects : MonoBehaviour
{
void OnTriggerEnter(Collider other)
{
Debug.Log("I have collided with something!");
// Check if the GameObject has collided with another GameObject
if (other.CompareTag("Car") || other.CompareTag("Obstacle"))
{
Debug.Log("I have the tag");
// Get the size of the current GameObject and the other GameObject
float mySize = transform.localScale.magnitude;
float otherSize = other.transform.localScale.magnitude;
// Check if the current GameObject is bigger than the other GameObject
if (mySize > otherSize)
{
Debug.Log("I ate the other GameObject!");
// "Eat" the other GameObject (destroy it)
Destroy(other.gameObject);
// Increase the size of the current GameObject (optional)
transform.localScale += Vector3.one * 0.1f; // Increase the scale by 0.1 units
}
}
}
}
none of the debugs happen
whats number 2 mean like how would i do that
You would tick the box that says isTrigger
on one of them
To use OnTrigger you need a trigger.
Otherwise use OnCollision
then I don't even know what I was doing because I was doing something like
public void UpdateInspectableVariableValue(string variableName, string newValue)
{
Type type = GetType();
FieldInfo field = type.GetField(variableName, BindingFlags.Public | BindingFlags.Instance);
}
With no errors or anything
What are you even trying to do here
basically set the variable value just by knowing the variable name
You probably shouldn't use reflection in a game, it's quite slow and very error prone. If you want to get a variable by name its probably better to store it in a dictionary
Tbh, at first I was going to do that, and I indeed did start with just referencing the variables. But once the number of variables I have to modify in-game with the UI increases, the work and chaos behind every single addition to a MissionEditor increases exponentially😅
u change that variable in same class u got that method in worst case shoulda been a switch or something 
what?😅
private string var2;
public void UpdateInspectableVariableValue(string variableName, string newValue)
{
switch (variableName)
{
case "var1": var1 = newValue; break;
case "var2": var2 = newValue; break;
}
}```
as brittle as reflection but not reflection so a step forward 
damn thats a lot huh
for every script that can be changed
dictionary ?
does unityevent.ivoke() get called every frame if on update?
and every time I want to add something new I have to manually all those variables
like, the problem I was facing was the ability to add more things easily
it should
how do u store ref to a variable in dict
ok thank you
Okay new question (sorry haha), is there a way to set a static value externally?
Like I have this inside a class:
public static VariableManipulator inst;
And I want to set that inst value from another script. Is that possible?
of course
just set it
with =
It's not really good practice to have random puvlid static variables being set from all over the place though
gets very difficult to track
why this then 😦
vm is an instance
doesnt make sense
To set a static variable you use the class name
which is probably what your red squiggle is saying
VariableManipulator.inst = vm;```
ahhhh okay mb
but i don't understand why you would do it like this
I'm so dumb lol
why don't you do cs public static readonly VariableManipulator inst = new(); directly in the class
why have some other class initialize it?
Seems weird
because otherwise a reference to the inst is called before it is acutally set
you can also just call Setup directly in the constructor
not possible the way I just showed you
yeah that's exactly what I was doing but that was causing said problem
like I had this: ```c
if(VariableManipulator.inst == null)
{
VariableManipulator vm = new();
vm.Setup();
}
and then in the VariableManipulator script :
```c
public void Setup()
{
inst = this;
}
but the code just after the if was called before the setup was done aparently
I have a problem and it is when I go to get the distance to the mesh to place objects, it happens before the mesh will load in and does not like it, I found out that i can't use while to fix this either
yeah this is wrong
do it like my example
!vscode
if (Gamecontrols.GamePlay.Crouch.WasPressedThisFrame() && isGrounded && enableCrouch)
{
Crouch();
}
public void Crouch()
{
if (isCrouched)
{
transform.localScale = new Vector3(originalScale.x, originalScale.y, originalScale.z);
playerSpeed = targetedWalkSpeed;
isCrouched = false;
}
else
{
transform.localScale = new Vector3(originalScale.x, 0.9f, originalScale.z);
playerSpeed = crouchSpeed;
isCrouched = true;
}
}
``` Why does pressing the "Crouch Key" sometimes not work, if you spam it?
Is this code in FixedUpdate?
Yes
Move it to update and it should behave better
Okay, thanks.
Fixed Update is for Physics related stuff it's better to not check for Input in there
Vector3 movePos = hit.transform ? hit.point - _projectileOrigin.transform.position : ray.direction;
Running into an issue where the projectile moves at extremely different speed if there is a hit. Also I would like to note that I'm not using lerp.
Yep that completely fixed it, Thanks.
Ofc brother!
how do we go from movePos to direction here ??
yo need to share more code
also why is it called movePos if it's actually a direction vector?
sorry its a bit messy let me create a cleaner version
just share the full script
Gun
{
Projectile projectile = Instantiate(_projectilePrefab);
Ray ray = new Ray(_projectileOrigin.position, Camera.main.transform.forward + Calculations.GetSpread(_profile.Spread));
RaycastHit hit = Calculations.Raycast(Camera.main.transform.position, Camera.main.transform.forward + Calculations.GetSpread(_profile.Spread));
Quaternion startRot = hit.transform ? Quaternion.LookRotation(hit.point - _projectileOrigin.transform.position) : Quaternion.LookRotation(ray.direction);
Vector3 moveDirection = hit.transform ? hit.point - _projectileOrigin.transform.position : ray.direction;
projectile.SetUp(_profile.Damage);
projectile.Initialize(_projectileOrigin.position, startRot, moveDirection, _projectileSpeed);
}```
Projectile
{
transform.position = startPos;
transform.rotation = startRot;
StartCoroutine(Move(direction, speed));
}
private IEnumerator Move(Vector3 direction, float speed)
{
while (true)
{
transform.position += direction * speed * Time.deltaTime;
yield return new WaitForEndOfFrame();
}
}```
You're not normalizing moveDirection
so the magnitude is different when you do the subtraction
Vector3 moveDirection = hit.transform ? (hit.point - _projectileOrigin.transform.position).normalized : ray.direction;```
ill give it a shot
is there a way / how would I Instantiate an animator controller transition between two states from code?
using animator params
"instantiate"?
the transition is not a unity object
are you trying to modify an animator controller at runtime?
perhaps you just want to manually switch to a specific state?
explain your use case.
sorry I was using instantiate as a generic term not as the method name
I was trying to make an attack system with many different / unique animations, and was trying to store the animations on their specific weapons instead of a massive state machine with 100s of transitions. to do that I need to be able to acess a blend tree in code, add motions to it and set a float param (all of which I have gotten working), I was just trying to make it a bit easier on myself and also create that blend tree from code aswell. (instead of setting one up on every single character that can use the weapon)... Though from what I understand I will also need a transition to that tree/state to get it to work fluidly with the rest of the animator
at that point i'd just use animator.Play to manually enter states as needed
My OnTriggerEnter function is not working as it is supposed to collect an item on the floor
I was a little hesitant to do that since I dont want to interrupt certain states IE jumping. Would I still be able to check if certain states are running?
Sure.
https://docs.unity3d.com/ScriptReference/Animations.AnimatorState-transitions.html you may be able to modify this
i dunno if this will mutate the asset
you should figure out the physics setting. you have to attach at least one rigidbody component and have to set the layers to collide.
so you may want to instantiate the animator controller before mucking with it
thank you, as always ❤️
Yes, I have a rigidbody component and a box collider component on the game object
you should set the layers of two gameobjects to collide.
Sorry, wdym?
Hey Sam are you making a 2D or 3D game?
3D
and then you should consider this.
okay, so the rigidbody is probably not falling asleep and preventing the triggers from happening
(that happens in 2D)
Is trigger set on the box collider?
Yes
Can we see the code?
Do triggers work at all? Like have u tried putting a print() or Debug.Log() in the trigger? Just to make sure triggers are at least working?
The trigger does seem to work
can you share your screen of physics setting window, and hierachy of two gameobjects including layername, rigidbody component, collider component~
Yes, also only my object I want to collect had a box collider
That is from the collectible item
What do you guys think?
the blue line on the left indicates this is a prefab override
shouldn't it be set as a trigger in the prefab itself?
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("CollectibleCell"))
{
Debug.Log("Trigger entered by CollectibleCell.");
Destroy(gameObject);
}
else
{
Debug.Log("Trigger entered by something else.");
}
}
so what is printing?
Printing?
Whats the console saying
Oh
Does ur item have the correct tag?
I try to avoid using tags i usually use interfaces for items if ur familiar with interfaces
how do I use the Character Controller component to move in the direction the object is pointing and not straight up or down.
The tag is correct
Show us the tag
clearly not
transform.forward
cc.Move(tansform.forward * speed * Input.GetAxis("Vertical") * Time.deltaTime
(Don't copy just an example - don't do inline like this)
yeah but this is probably not the object you are colliding with
The cell should destroy when the player touches it
I want to instantiate cameras and set render textures for them can I assign this in code?
right but the trigger isnt detecting the cell
Debug.Log($"{name} was hit by {other.name} that had a tag of {other.tag}", other);```
ok well; it's going to need the proper tag for that to work
show the whole inspector for the object
with the collider and the tag etc
Is ur cell the one with the trigger?
also printing the tag you hit in the log is a good idea
Yes
prove it
Ur checking if the cell entered the cell
wait is this cript on the collectible itself?
Why would it need to check its own tag?
Yes
Hi guys, my bullet is a prefab and I do not know how to give it commands from an object that isn't it just won't let me. That's why when the player stops (all stuff should be slowed down) the bullet doesn't. How can I fix this?
https://hatebin.com/hfwumdsqek (player code)
https://hatebin.com/vrfmksygyo (bullet code)
Change CompareTag() to accept the players tag
gonna be honest watched your videos and read your coder and I have no idea what you're asking
Ik that but I am asking how can I change it
what "command" are you trying to give?
My player code
What object are you trying to give it from and to?
I cant give it to my bullet prefab
And it can't get a variable from the player code
Where is the code that spawns the bullet?>
script
It's not in the script you shared
wht do you mean "give script"?
Be speciific please
what information are you trying to share?
for what purpose?
I want to give the bullet the player script so that it can access code from the player
Because when my player has velocity.magnitude = 0 all slows down to 0.1x
ANd I want to have a bool
that code isn't anywhere in the scripts you shared
when it is true that means
You need to share the code that is relevant to the problem
this isn't it
where is the slow motion stuff happening?
player code
this is not something the bullet needs to care about
In the second video I show
i did that and now it works, it just wont let me control it anymore and moves upward with out any input.
Vector3 move = new Vector3(0, Input.GetAxis("Vertical"), 0);
characterController.Move(transform.up * Time.deltaTime * Speed);
why aren't you just using Time.timeScale?
Hi, currently i'm trying to make sorting work but it doesn't work xd Tilemap with trees and stuff is in same layer as player sprite.
What is that
It's the way you should be slowing the game down
But how can I give the function to tell the bullet that the player isn't moving
wait is this 2D? why are you doing up..
you don't need to
well, you don't use move anywhere in line 2, so of course it ignores your input!
wdym
Time.timeScale = 0.1f;
okay lemme try
would i just add move * or do i have to do something else?
Having move there is kind of important lol thats what makees it not move because Input = 0 then everything is 0
@magic stream
stuff * 0 = 0
Alright, I changed the tag to main camera which is the player so now it should be working? Should I nowmove the script from the cell to the player?
Look up auto sorting on youtube
i've tried everything
Have u tried what i just reccomended ?
Its a Render Feature in Unity
I dont know if thats the correct term but basically Uinty has already coded this for u
i know
U just have to enable it
So uve tried it then?
Im not talking about the sprite Renderers layer field
this doesnt work, am i putting move in wrong?
but issue is probably that my project isn't URP, maybe it doesn't make any difference idk xd
If ur projects not in URP....
Then idk ive tried coding a system like that myself but its a pain
what is dis guys...
Are you randomly doing stuff? Maybe lookup a tutorial 
it sends me to some randoom place
how come you're doing .up ?
have you read the error message?
Ideally, it'd simply be the direction multiple by speed and delta time.
i want it to move in the direction it is pointing upwards, and it did but it didnt take in my input.
Yep I don't get
the Scene object you passed into MoveGameObjectToScene was not a valid scene
It doesn't even tell me what object
@azure zenith the player is the camera?
Wherever you got it from was wrong
Sorry no, the player is the player lol
Also, I get the correct log statement now
It doesn't disappear though but I'll see why
It doesn't slow everything down
what isn't slowing?
My bullet
Thank you all for helping
this I think gives you an error.
Since your bullet is simply moving via rigidbody velocity, it should indeed slow
@frank light did you check console ?
maybe you never set the time scale
it gives me a syntax error
yes you can't multiply two vectors
you can't just mash together random variables
show the code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerCode : MonoBehaviour
{
public InputActionReference gamepadRight;
public bool dead = false;
public bool moving;
public GameObject mouse;
private float dirX = 0f;
private float virX = 0;
private Rigidbody2D rb;
[SerializeField] private float moveSpeed = 15f;
// Start is called before the first frame update
void Start()
{
dead = false;
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
Vector3 worldPos = new Vector3(mouse.transform.position.x,mouse.transform.position.y,0);
move();
slowmo();
transform.right = (worldPos - transform.position).normalized;
}
void move()
{
dirX = Input.GetAxisRaw("Horizontal");
virX = Input.GetAxisRaw("Vertical");
Vector3 moveDir = new Vector3(dirX, virX).normalized;
rb.velocity = moveDir * moveSpeed;
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Bullet"))
{
die();
}
}
void die()
{
dead = true;
Destroy(gameObject);
}
void slowmo()
{
Vector2 vel = rb.velocity;
if (vel.magnitude == 0)
{
Debug.Log("Still");
moving = false;
}
else
{
Debug.Log("Moving");
moving = true;
}
}
}
LIke this?
stop and think about what you are doing.
@frank light you have to use move.y
instead of move?
since its a float
yes you can't do move * transform.up if move is vector3
so you need move.y
Ohh mb i put the code in bullet not player sr
yeah it needs to go in the slowmo function
isn’t transform.up a vector 3
oh i see what he’s going for
thank you it works now navarone you are helpful
i also recommend you separate player movment from player life/death code
yep mb
both player movement and life/death can get really complex as you build in more features, and the two don’t have much to do with each other, besides death asking movement to just hard stop
me looking back at my earlier projects with classees spanning over 800 lines long xD
what the hell was single responsibility ?
those are the worst
i inheritted code that used a fuckload of booleans… instead of an enum
its like looking at an old high school photo with bad haircut and clothes and thought it was "cool"
untangling that was a mess
enums are underrated
Is there a way to serialize a field to assign a Scene to a reference?
I'm trying to use 1 script to handle zone transitions from different locations in a scene and I'm trying to work out the best way to handle the whole "door A goes here, door B goes here" without hard coding or creating a bunch of specific scripts for it
not really
sounds like you need to re-think this system
what I have done is make a static class with a bunch of public constants, where each constant corresponds to the specific number of a given scene
and also, you want extremely few scenes in a game
Oh i used strings for mine^
like, single digit
Wait really?
you can’t use strings. you need an int for build index
You can load scenes by name?
constants let you call those ints by using something like SceneIndices.MainMenu
First time I've heard that
and then it spits out the scene index for main menu, which is 0
ok, you want extremely few scenes
i’m telling you now
Actually I've found most people drastically underutilize scenes. Most people could stand to use more scenes
Well I mean if there's no way to do that then I guess I do. I'm just starting to work on it, like today. Lol
because every time you change scenes, you have to deal with everything getting destroyed, and managing references to/from things that should/shouldn’t be destroyed
I mean....yeah
and that’s a pain in the ass
But what about stuff you dont want in a scene? It would make sense to get rid of it
what stuff do you not want in a scene
Load Additive 😛
Not with proper comparmentalizing of data and additive scene loading
If I'm completely changing zones in a platformer, I don't want the old zone assets sitting around the entire time
Level Based games? Neon White for example (Made in Unity) has over 200 levels
exactly. That’s why I load a level file into the scene, so the scene can load everything about the new level
I highly doubt they combine levels into singular scenes
Additive scene loading is goated.
Even Open world games are split into multiple scenes
if a lot of the assets you put are manually placed, then you probably want additive scene loading
makes it easier to collab on map
A scene should be thought of as a "loading point". If you have more smaller scenes you can dynamically load and unload them. For example, Metroid Prime has something analogous to "scenes" for each room in the game. When you shoot a door, it loads that room async and additively. When the door shuts behind you, it unloads the old room
This has the cost of requiring some load buffer/scenes.
So you'd have hundreds of scenes for a game like that
take a look at how they made Firewatch, its split into multiple senes
Yeah im familair ^^
Load additive was the next thing I have questions about. I read recently a solution that involved creating a "base" scene that has all your don't destory stuff like player, cameras, audio, etc, then just loading additive scenes around it? Is that common?
Ive seen there talks
Have u seen the fucking animation system for that game
Its insane
bonzai nest
it depends on how you make everything. A scene is like a giant mega prefab
Ive never heard off additive scene loading but it sounds interesting
you probably don't want many exclusively loaded scenes if you don't have nice distinct levels, since switching between those is, indeed, going to make everything go away
DDOL just measn they live in their own scene
i mean, just using DontDestroyOnLoad is already doing additive scene loading
Thats what i figured^^
Ok, that makes sense actually
it punts the object into a scene that never unloads
Hi there, i am currently trying to make a script so that when the player touches an object, it increases a varaible in the same script by one. However, i am having some trouble doing so. I have attatched an image with my code as well
IS ur game in 2D or 3D?
3D
The Three Commandments of OnTriggerEnter:
- Thou Shalt have a 3D Collider on each object
- Thou Shalt tick
isTriggeron at least one of them - Thou Shalt have a 3D Rigidbody on at least one of them
In general, more scenes = more problems. So you want to avoid separate scenes unless you have a good reason.
I'm not sure. I have some code later so the player speed is changed by a modifier that is 1+(speed items * 0.2)
Thanks
i am having some trouble doing so
What kind of trouble?
I grabbed this code from another project, and it was set to do something else. Eventually i am going to have the triggering item dissapear as well
One second
There is so much wrong with this code the more I look
Yeah like im confused
Show the BloonData for a green balloon
You've ended the method and if statement with a semicolon
you have a lot of problems with your code:
- You have a semicolon after your if statement
- you have an
elseattached to nothing - you have a statement that just says
null;???
Bro lmao
looks like basic compile errors
Tbh im not entirely sure what im doing
first step is to configure your IDE
Its ok homie
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
Yeah you need to configure your !ide so it will stop you from making basic compile errors
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
Okay, now double click that blue prefab and show me the inspector of the thing it opens
Okay, now double click that BlueBloon variable and show me the inspector of that one
First, it might help to call a public method Death() instead of Destroy(gameObject). This way you aren’t worried about things not being arround when you need them
Okay, and you've been clicking on these objects in the variables, right? Just to make sure you don't have two things named BlueBloon for example
Just wanted to make sure
Are you actually getting an error?
If so, you should post that
Can you show what the console looks like after killing a green balloon, and then the blue balloon it makes?
Im on mac using VS Code, and im not really seeing how to configure the ide
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
Im going throught the jetbrains rider, but i dont know how to install it
why do you even need a last position variable?
Why
Why are you going through Rider if you're using VSCode
Nah, I just want to see what those logs say
If you have logs that aren't in this script, maybe disable them
Did you try clicking on VS Code
The VS Code is not a HEADER that's a link
🤦♂️
Lol, I mean... I can KIND of understand that one
again: why do you need a last position variable
I'm not seeing anything ChildBalloon Position =
Are you sure there's no errors that are hidden
I am also unsure how to pull up the preferences window on mac
Likely his instantiation uses a cache of position which isn't properly updated beyond the original bloon
probably
Okay, so it is reaching that step
also, you need to comment your code, dude. Move vs Move2 makes no sense
comment + better name
I need to upgrade my unity version but my computer is SO slow
Let's level up those debug logs, replace your function with this:
public void OnDestroy()
{
revive += 1;
if (BloonData.Children != null) // Check if the balloon has any children
{
GameObject ChildBalloon = Instantiate(BloonData.Children, lastPosition, transform.rotation);
Bloons ChildBalloonScript = ChildBalloon.GetComponent<Bloons>();
ChildBalloonScript.revive = revive;
ChildBalloonScript.lastIndex = lastIndex;
ChildBalloonScript.lastPosition = lastPosition;
Debug.Log($"{gameObject.name} has been destroyed. Spawning in {ChildBalloon.name} at position {lastPosition}");
}
}
So instead of switching to small scenes for things like inside a house in town, would you suggest just additive load the scene else where in the existing scene and porting player/switching camera there?
Or just having the "interior" scenes built in the same scene space and jumping there when needed?
additive load
i guess it depends on how big the inner house is
Or have inactive objects and enable them
Yes, and then do the same process, kill a green balloon, then the blue one, and look in the console for that section of logs
Yea, they aren't big
If the scenes were designed separately, then you'd want to load them additively
yeah, I would make a class to just log everything part of a given layer of loading
Instantiation isn't expensive (unless you're computing crazy stuff), GC collecting is.
like one class that just has references to everything in the city. On load house, make them all don’t destroy on load, load house scene. Repeat
My VS code was in safe ir untrusted mode, blocking soem pluggins. When i put it into trusted mode it says sign in to access VS code benefits as well and nowsome of my pluggins say preview, including Unity. Will this be an issue?
unity plugin is still in preview yes
its normal
Ok
up to you if want to sign in or not to save ur settings
Ok, thanks
I always keep an entity ledger class
I've only just started working on these additional scenes so I only have 1 so far, just trying to work out the best way to pull it in. It was also my first time using a tile set map specifically with these interior scenes so hopefully that doesn't mess things up. I'll try bringing it into the main scene a few different ways and see how things go. Thanks everyone
EntityLedger singleton. Everything that spawns has a SpawnedEntityHandler, and logs itself to the entity ledger upon being spawned, and unlogs when despawned.
instantiating in OnDestroy leads to sadness 😦
should do it in a separate Die() function instead
Looks like it spawned in the red one just fine.
Makes it super easy to controlled destroy/despawn everything temporary in a scene
agreed
Yes, that is one of the many follow-ups I'm going to suggest, along with changing all those prefabs of type GameObject to just be Bloons
Yeah, I think it's time we move into this problem sooner rather than later
You shouldn't be doing this in OnDestroy. You should make this function something like OnDeath() and manually call it before Destroying an object in code
so it doesn't get called whenever the scene changes
in general, I try to do very little during OnDestroy because you don’t know how much shit has already stopped existing
It's a good place to unsubscrive from things
You just need to be paranoid with if (thing != null) checks in OnDestroy
i mostly use OnDestroy as an emergency: “make sure we unsubscribe and let everything know we are dead if every other check failed” sort of thing
normal death/despawn is handled through methods that get called before any Destroy calls go out
no
public event Action OnDeath;
public void Death() {
do whatever you need to do when you are dying;
OnDeath?.Invoke();
Destroy(gameObject)}
Rename your OnDestroy method to Death
The suggestion was made to simply avoid the OnDestroy callback.
and then manually call it when you defeat a balloon
This isn't merely to factor code into a different function, just to be clear.
Can someone suggest me a way i can learn c# sharp for unity?
Check the pins
factoring the code into a different callback lets you avoid using OnDestroy
C##. 
yes
Correct. They still do that, but now they should also call Death() on that object
it’s not the most spaghetti, but you should do better before you are too far gone
no. they call Death(), not destroy at all. Death is responsible for calling destroy
Understandable but I'm clarifying that the below isn't what we're simply trying to achieve cs void OnDestroy() => Death();🥹
It wouldn't matter either way, as long as it dying and it being destroyed are separate things
yeah that’s wrong
Death should centralize it. It isn’t the projectile’s job to handle destroying the thing. It’s the bloon’s job to know what to do when it’s supposed to die
projectile just needs to notify bloon about this request to die
it sounds semantic, but I think it is important
Hi how do I transfer data into one scene to another? Like lets say I have 2 gold coins in one scene and I want to transfer that to a different scene
DDOL or ScriptableObject
GetComponent<BloonScript>().Death();
that is all projectile needs to do
Not sure, I'd just do the below in a health property cs _health = value; if (_health < 1) { Dead(); Destroy(gameObject);//or decommission to object pool }
whats DDOL?
Dont Destroy On Load
What pins
in this channel
The pinned messages of this discord channel
thx
Is the BloonsScript on the object this script is on?
You'd probably still want to call destroy on the bloon
it's happening in OnDeath
Ah alright
I wasn't aware of the progress that's been made
Probably whatever's being destroyed doesn't have the component
should be collision.collider.GetComponent<Bloons>()
not just GetComponent<Bloons>()
And what line is 31?
Does this object have a Bloons script on it
It definitely isn't related to code - #💻┃unity-talk
Ok, i wasnt sure if that fit. Thanks
how would i make it so when i collide with something a certain thing only happens if im bigger then them
You are currently trying to get the Bloons component from this object, and since it doesn't have one, that's your error. You probably want to get the Bloons component from the object you collided with
if bigger than target
do certain thing```
no like actual code lol
If they have colliders, get the colliders bounds. Then, you can get bounds.size to get the width and height. From there, decide if you want to know if the area is bigger (multiply size.x and size.y before comparing) or if you want it to be bigger on at least one axis (check size.x and size.y separately)
Which part?
The on collision enter callback, size comparison or the do certain thing?
the size comparison
I'm assuming you've researched this are doing some sort of bounds comparison
Checking collider bounds lets you compare the size of objects even if their meshes have different scales
float otherSize = Mathf.Max(collision.collider.bounds.size.x, collision.collider.bounds.size.y, collision.collider.bounds.size.z);
float thisSize = Mathf.Max(transform.localScale.x, transform.localScale.y, transform.localScale.z);
if (thisSize > otherSize * crushThreshold)
``` tried this is doesnt work
If you're using bounds, use bounds for both
Scale and size are not necessarily comparable
so how do i get my objects bounds
aight thanks i gtg for a little
Can someone help me with this?
I'm copying a tutorial to learn movement... I don't think I did anything wrong, and all my attempted fixes kind of just break it more?
you did something wrong
My game starts off with having 0 grenades. When I collect a grenade, it should increase the amount of grenades I have but I get an error: NullReferenceException: Object reference not set to an instance of an object
That's what I don't know
is it a list ? its probably not initialized
the first thing you need to do is finish configuring your IDE
Your editor is not configured. Configure it first (see bot message below)
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
nooooo
It is an int variable set to 0
yeeeees
show which line that error is
Show the line the error is on
Try again, it saved a lot of headaches.
you need to read the full error message which includes a filename and line number for the error
Okay, one sec
So what is powerCellCollectible.cs line 13
I trust windows with my life now, but visual studio sees no problems. only unity
shooterScript is null
btw you are making lots of typos. That's why you need to configure your IDE:
if it was configured this would be underlined in red
you would also have autocomplete
Because it is not configured 🤷♂️
It is set to 1 actually
shooterScript cannot be set to 1
Because 1 has no property named no_cell
Okay, so, the red one's invincible. Where do you destroy the balloons?
Get rid of lastPosition and use transform.position as the second parameter to Instantiate
should i do that in my script or make a seperate script for that
Well, you want to know this object's bounds in this script don't you
yeah just didnt know if it was meant to be a seperate one lol still new
Just wanna throw this out there since it seems you're making a btd clone. if you plan to add projectiles that do more than 1 damage, you're gonna have to add more to this method so that it checks how many layers to destroy. Having it go through each children is gonna be slow if something eventually can deal 10 damage
smth like this would work
m_Collider = GetComponent<Collider>();
m_Size = m_Collider.bounds.size;
float thisSize = Mathf.Max(m_Size.x, m_Size.y, m_Size.z);
do you mean skip through layers ie if the projectile is 2 damage a green balloon goes straight to a red balloon

Yes, in your current method this isnt possible. You could try to get the child of a child (doing this equal to the number of damage you do) but theres probably a faster alternative instead of going through what I assume is data on a prefab. Itd be better if you could have some function used to calculate which layer it should go to
how do i give a object a rigidbody but have it stay still
What are you adding a rigidbody for? Weren't you already detecting collisions?
well was gonna do it so i could disable its movement
but i guess i can just do another if for if its a car
hi everyone! 😄
can someone guide me please!
a week ago i start to code again and notice my IntelliSense has stopped working. 🥲
i looked around and notice unity removed the visualcode package and so on.. 🧐
i fixed it by installing the visual studio editor 2.0.22 for unity and unity extensions and c# dev and .net SDK 8 (i already had 6 and 7). 😉
BUT NOW it has stopped working again. 😖
i checked the prefrences and everything.
i thought it beacuse c# dev preview version so i installed it BUT it still not working. 😭
how should i fix it? 😟
!ide
Things changed drastically in August. Redo the guide
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
ok its weird this is what i get the balls size is 4.92001 and the cars size is 9.673187 how do i fix that cause rn if its super long it counts as bigger
using UnityEngine;
public class CrushObjects : MonoBehaviour
{
public float crushThreshold = 2f; // Size threshold for crushing
Collider m_Collider;
Vector3 m_Center;
Vector3 m_Size, m_Min, m_Max;
void OnCollisionEnter(Collision collision)
{
// Calculate the size of the colliding object
float otherSize = Mathf.Max(collision.collider.bounds.size.x, collision.collider.bounds.size.y, collision.collider.bounds.size.z);
// Calculate the size of the current object
m_Collider = GetComponent<Collider>();
m_Size = m_Collider.bounds.size;
float thisSize = Mathf.Max(m_Size.x, m_Size.y, m_Size.z);
//float thisSize = Mathf.Max(transform.localScale.x, transform.localScale.y, transform.localScale.z);
Debug.Log("This size: " + thisSize);
Debug.Log("Other size: " + otherSize);
// Check if the current object is bigger than the colliding object
if (thisSize > otherSize * crushThreshold)
{
// Crush the object by disabling its Rigidbody and Collider components
collision.collider.enabled = false;
// Optionally, you can add more crush effects or actions here
Debug.Log("Object crushed!");
}
}
}
``` my code
Well, you are taking the largest axis, what do you expect would happen
I WAS wondering why you were using Max
nice gpt code
Compare the size of the bounds?
what do you consider one thing must be to be bigger than another?
wdym
As I said, you're going to have to decide how you want to know when something is bigger
it was a joke, because of your code comments
Why min or max or anything? Don't you want size?
bounds.size
oh yeah i put my code into chatgpt to have it write comments for me makes it easier
eh code should be pretty self explanitory what its doing
gpt comments are as useful as a car without gas
yeah i use bounds.size
I know i followed it last time and got fixed but it's not working again!
You use it INSIDE max though... just don't, and compare it directly
How long ago?
Could just need to regenerate project files
4 or 5 days ago
Ok yeah. Go to External tools and click regerenerat project files
then there are errors though
I'll try it thank you. 🌹
Because otherSize is a float, and you're trying to set it to a tuple of three floats
Again, you're going to need to think about what makes something "bigger". How do you define "bigger"
Why are you even trying that? What benefit would doing that have? That is breaking up the axes of the size and putting them in a tuple and trying to assign that to a float....
taller i guess
Okay, so that's the Y size
So check if the Y size is bigger than the other
basically if your bigger then you can obsorb the smaller thing
Define "bigger"
so a 1m tall 1cm round pole can absorb a 50cm high 400km wide cube?
thats why idk what to do for it
so think, it's your game, you decide
This isn't something we can answer. You need to decide what you want "bigger" to mean
alright thanks i can figure this out with this info
Once you know what "bigger" means, we can try to help with how to implement it, but we can't decide it for you
so object volume
Hey guys i have a question. i have some code for an enemy but not sure if it is correct or not and i have nothing to test it on. can you tell me if its okay?
#💻┃code-beginner message
Then the truck should not be comsumed by the ball here, which is apparently not what is wanted
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemigo : MonoBehaviour
{
private int hp;
void Start()
{
hp = 100;
}
public void Recibirdaño()
{
hp = hp - 25;
if (hp <= 0)
{
this.desaparece();
}
}
private void desaparece()
{
Destroy(gameObject);
}
void Update()
{
}
}
What is the problem
I am unsure if its correct or not. but i believe it is?
I have nothing to try it on 💀 thats why. i did this before doing a raycasting to try and see if i can kill it.
What does "correct" mean for you?
So then work on making something to try it on
If you don't have anything that can run it then it doesn't matter if it's correct or not
as in uh. "it will work"
Well, right now it won't work, because it apparently does not exist
fair enough. ill code a raycasting and see
It will work as written. As all code does.
hey so for my cars it works fine but if i try to do it to smth like a fire hydrant it doesnt work for it only difference between the 2 is model of course and the car has a car controller and a rigidbody
using UnityEngine;
public class CrushObjects : MonoBehaviour
{
public float crushThreshold = 2f; // Size threshold for crushing
Collider m_Collider;
Vector3 m_Center;
Vector3 m_Size, m_Min, m_Max;
void OnCollisionEnter(Collision collision)
{
// Calculate the size of the colliding object
//float otherSize = Mathf.Min(collision.collider.bounds.size.x, collision.collider.bounds.size.y, collision.collider.bounds.size.z);
float otherSize = (collision.collider.bounds.size.y);
// Calculate the size of the current object
m_Collider = GetComponent<Collider>();
m_Size = m_Collider.bounds.size;
//float thisSize = Mathf.Min(m_Size.x, m_Size.y, m_Size.z);
float thisSize = (m_Size.y);
//float thisSize = Mathf.Max(transform.localScale.x, transform.localScale.y, transform.localScale.z);
Debug.Log("This size: " + thisSize);
Debug.Log("Other size: " + otherSize);
// Check if the current object is bigger than the colliding object
//if (thisSize > otherSize * crushThreshold)
if (thisSize > otherSize)
{
// Crush the object by disabling its Rigidbody and Collider components
collision.collider.enabled = false;
// Optionally, you can add more crush effects or actions here
Debug.Log("Object crushed!");
}
}
}
Does the other object have a rigidbody
so the object colliding with it has a character controller does that act as a rigid body
adding this ```csharp
if (hit.gameObject.CompareTag("Car") || hit.gameObject.CompareTag("Obstacle"))
i have a question guys. i have declared the var "hit" but its not in use. where should i uh or rather, how do i fix that? i searched on the microsoft thing and it explains how you get the error but not how to fix it. 💀
And im unsure if i should fix it "from" the rayray script or make a whole new script for "if you get hit X happens"
its a warning u got variable u dont need if its like a parameter u need to include u can make it a discard "_"
If it's not being used then it doesn't need to exist
But i want it to use it so the rayray can hit stuff and eliminate it.
So then use it
😲

Assuming raycast. If you do not need to access info of what you hit, discard the out parameter.
if (Physics.Raycast(origin, direction, out _, distance, mask))
// ...
THere's also a version of raycast that doesn't have the out param
nuka cola?
Is there a best way to apply motion to a character for a 2d sidescroller? I've tried using addforce and changing the velocity of the rigid body separately and both just didn't feel like what I was looking for. Is this usually something that is done from scratch making your own system?
I guess depends what you're after.
Dynamic rb are tricky but have their benefits, what exactly are you looking for ?
I found that using AddForce is better with Acceleration/Force mode
Hollow Knight, responsive, fast
it's hard getting that feel while battling physics is what I am finding.
I feel like I am having a hard time finding a balance between weight, friction, etc
thats usually the downsides. I think thats a custom controller
make custom controls, the hard part is learning about the essentials like coyote time and all that
I find that using Animation Curve on speeds like movement makes it feel more natural if you want accelerations, or fake slowing down/friction
Thanks for the tips, Ill do some more research.
Hey I needed help with a script. So I have 3 walls & a floor having "WallLayer" & i have a spherePrefab which is being instantiated on one of the walls. The spherePrefab is on PrefabLayer. Now I want to be able to drag this sphere onto any of these 4 walls. The problem I am running into is that when I attempt to click & drag this sphere another perfab is instantiated. Unity thinks I'm clicking on WallLayer when I actaully am clicking on PrefabLayer. How do I tackle this?
public class DraggableEndPoint : MonoBehaviour
{
private bool isDragging = false;
private Material originalMaterial;
private Color originalColor;
void Start()
{
originalMaterial = GetComponent<Renderer>().material;
originalColor = originalMaterial.color;
}
void OnMouseDrag()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (isDragging && Physics.Raycast(ray, out hit, Mathf.Infinity, LayerMask.GetMask("WallLayer")))
{
Vector3 hitPoint = hit.point;
gameObject.transform.position = hitPoint;
}
}
void OnMouseDown()
{
if (gameObject.layer == LayerMask.NameToLayer("EndPointLayer"))
{
isDragging = true;
GetComponent<Renderer>().material.color = Color.black;
}
}
void OnMouseUp()
{
if (gameObject.layer == LayerMask.NameToLayer("EndPointLayer"))
{
isDragging = false;
GetComponent<Renderer>().material.color = originalColor;
}
}
}
public class LeftWallController : MonoBehaviour
{
public GameObject lineEndPointPrefab;
private GameObject currentSphere;
void Update()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Input.GetMouseButtonDown(0))
{
if (Physics.Raycast(ray, out hit, Mathf.Infinity, LayerMask.GetMask("WallLayer")))
{
// Check if the hit object is on the WallLayer
if (hit.collider.gameObject.layer == LayerMask.NameToLayer("WallLayer") && hit.collider.gameObject == gameObject)
{
Vector3 hitPoint = hit.point;
currentSphere = Instantiate(lineEndPointPrefab, hitPoint, Quaternion.identity);
}
}
}
}
}```
I gave my camera a kinematic rigidbody, and have it moveposition towards a camera target
i use lerp to get a position closer to player + an offset. And I clean up that position by getting the closest position within level bounds to that position
i set a variable for camtarget. So CamTarget can be set to follow the transform of a player. Or for autoscroll, you set cam target to some invisible gameobject that moves
it is not cameraController’s job to find out what the target is supposed to be. That’s someone else’s job
I also split CameraTarget to CamTargetX and CamTargetY. This way you can have sidescrolling in X, while tracking the player’s Y coordinate.
i did tis but nothing Changed .
please look at this if anything is wrong tell me please.
I don't see visual studio in the package manager
Which is the only thing that matters in it haha
its in bottom
Not in that screenshot
Visual Studio, not Visual Scripting
And that is a TON of extensions
Also this screenshot is incredibly cursed, like there's 3 instances of VS code and weird extensions
I think they just collaged three screenshots after scrolling
Then yeah, it all looks good.
Only three things matter. The microsoft Unity extension, that package, and the External Tools being set
well i didnt wanted to send multiple screenshots to i put them to gather
Vs code just... has problems sometimes 🤷♂️
Try restarting your computer?
i have them all , then why its still not working?
i just turn it on again
Because Unity doesn't officially support vs code and microsoft is still working of implementing their own support? No idea. Lots of people have issues with it
It all LOOKS right. It SHOULD work
so if i change to visual studio itself it might work?
Visual Studio is directly supported and should work yeah. I HAVE seen people have issues with it too though
wdymlag? things in reallife don't lag lol
yeah its working with visual studio!
like a weapon sway ?
@summer stump thank you for your guidence!🌹🌹😘😘
yeah my guy
thats called weapon sway
this dude has uhhh premade script from gpt (oh nvm it was a joke on gpt, the script is in the description) seems to work
https://www.youtube.com/watch?v=LIWA1Rgy42A
What's your code look like
You can use [field: SerializeField] on your property implementations there, to expose the field in the Inspector without needing to make one yourself
[field: SerializeField]
public float Durability { get; set; }
field: instructs the compiler to put the attribute on the backing field that's auto-generated for the property
wait you can see values from interface in inspector?
yeah i didnt know either
oh nvm they mean the class under it
You can't. You put the attributes on the implementing properties in the class
yeah misread that xD I was about to sayy..
whats wrong with this then?