#💻┃code-beginner
1 messages · Page 71 of 1
So many possibilities. Gotta check them all.
Is it being frustum culled maybe..? Gotta check thoroughly.
what does that mean
When render bounds of renderers go outside the camera frustum(outside the camera view), they are culled.
ok, that seems like the most likely scenario
why doesn't it get refreshed when my object re-enters the view?
Sometimes render bounds don't actually aligns with visuals which would result in the object being culled. I'm not sure what renderer you use and how it's bounding box is generated though.
We do t even know if that's the case at all.
can someone help me with animations :s please
it would prob explain the object not disappearing when it's visible in the scene view :/
also, I am using urp
and cinemachine if that makes a diff
Doesn't really matter, but it might explain indeed.
I see, friend suggested that I have another camera that's positioned on the ground level at all times, would this even help if the camera output is not visible and how badly would this impact the mobile performance?
You could try logging something in OnBecameInvisible.
https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnBecameInvisible.html
If it logs when the issue occurs, then it's indeed being culled.
Wdym?
What's the point of another camera if nothing is visible in it?
well it would be visible but the camera's output wouldn't be rendered
that's why I was wondering if it would work in the first place
also
it does indeed become invisible
What's the point in the camera if it doesn't render anything?
Yeah, so you should research why your renderer is getting culled. Was that sprite renderer?
to prevent the object from disappearing
Wat?
it is a sprite renderer, I am using a closed sprite to generate the terrain
well it becomes invisible because it's getting culled, we were wondering if it being displaying on the other camera(that's not visible on the player's screen) would resolve the issue
a really bad solution but just an idea
Why not just make it visible in the current camera..?
that would affect what the player is seeing which is not what we want
how to make a text unvisible
how did you make it invisible in the first place
did i say it was invisible?
What do you mean? There's more and more info that you never explained and doesn't make sense in the context of the issue.
i was talking about making it visible in a script
so that if a player has no grapes
grapes are not shown
Ignore that one, a friend just suggested that I add another camera to the scene that would always be on the ground level and wouldn't be displayed to the player.
I was just wondering if that would even solve the issue if it's not being displayed.
It is a bad solution either way and just ignore it ig.
Whenever I collide with the Oxygen pickup. I get an error on line 49 which is oxygenController.UncreaseOxygen(increaseamount);
Is the player not supposed to see the terrain?
This is my IncreaseOxygen method in my oxygen controller
if it goes too high then no
shown in the vid I sent before, can link it again if you'd like
do you mean invisible?
Then who is supposed to see it when the player is too high?
cause i want it to be invisible by deafult
I mean one option would definitely be enabling the object through the script
always use TryGetComponent
eg
if(other.gameObject.TryGetComponent(out Oxygen oxygen)){
oxygen.IncreaseOxygen(icreaseAmount);
Destroy(gameObject); }```
cause the player starts with 0 grapes
how
you need a reference to it and then just call the _yourObject.SetActive(true/false);
it's still an object
select it in your scene, does it have a checkmark in the inspector(top left)?
are you getting any errors?
then it can be enabled/disabled
ok, would you mind showing me the piece of code you are using to toggle it and show me how you got a reference to your text?
nobody
my advice is maybe invert that if statement for cleaner code but just a preference:
if(!other.gameObject.TryGetComponent(out var oxygen)) return;
oxygen.IncreaseOxygen(icreaseAmount);
Destroy(gameObject);
the recommendation to use the TryGetComponent is good, what worries me is that you are making sure it's the player that you are getting the component from and it somehow doesn't have Oxygen component attached to it
are you sure you set everything up properly in the (possibly)prefab's inspector?
oh my.... Yep. you are right
happens
Rip to me. Thank you. The oxygen has nothing to do with the player. Will fix that now. THANK YOU
fixed
no joke. 12ish hours spent pulling my hair out. Need myself a Duck to talk to
wish I could say it never happened to me 😭
It sucks. Because I have way more complex things working and this is a rookie error 😅 Thank you though
but i want to do that with a script
we will do that with a script
can you tell me how?
btw this would not work with var without specifying a type
sure, we'll do that now
ok
are you sure?
oh I see
yes how the compiler know what type oxygen is
when using var you would use the <T>
you are using the TryGetComponent() not TryGetComponent<>(), my bad
I didn't even notice, my bad
i just feel like its too verbose so I put it in the out param
I'm not using var now. I just copied it from my healthscript out of frustration
it is cleaner that way, less text ig
i used fixedupdate to make the speed of a ball constant, but now if i want it to bounce it doesn’t
Would you mind sending us your code?
I am assuming that you are setting your ball's vel instead of adding to it.
ok, would you mind showing me how u get a ref to your text aswell as the code that is supposed to disable/enable it?
i found le answer
You should only assign velocity when you start and when you collide
no reason to be in fixedupdate
he said he wants his ball speed to be constant
yes I know that
it has to be constant but to be +1 every time it bounces
every time it bounces against the player*
thats why you would normalize the speed and then add it to a variable
I am positive that you can remove the * Time.deltaTime and erase the ForceMode2D.Impulse
it should do the same thing
talking about start
but if it's not in fixedupdate it's not a constant
and yeah
not true
dont use AddForce
chatgpt told me to use ForceMode2D. impulse lol
it isn't incorrect, just saying
and isn't time.deltatime use to make the speed not dependent on the fps?
rigidbody already have a fixed timestep
ForceMode2D.Force is the default, it already does that
oh ok
you would use Impulse if you wanted to add an instant force such as explosion for example
if you want to add a continuous force such as gravity then Force is better
so if i remove FixedUpdate it should be correct
I wouldn't use AddForce in pong like game
just use .velocity if you want equal speed until increase
wait
am i not using it already?
addforce is used only at void start
we said yesteday to remove it
you still have it for some reason
I usually don't use the FixedUpdate but it's far from wrong.
Unity doesn't update phyisics more often than the FixedUpdate happens so it's technically more performant.
Does it make a difference in a real world scenario?
Unlikely and just complicates the code imho.
i didn't see it
and what should i place at its place?
.velocity for an iniital move
is this what you're trying to make?
yup
yeah so use .velocity its best imo
you should prob store the velocity in a global variable(which is what n.n recommended earlier iirc)
here is how I do it, yours can be diff
private void Awake()
{
startPos = transform.position;
ResetBall();
}
public void ResetBall()
{
rb.MovePosition(startPos);
rb.velocity = Vector3.zero;
transform.Rotate(0, 0, Random.Range(-180f, 180f));
moveDir = transform.right * moveSpeed;
rb.velocity = moveDir;
}```
well not the velocity but direction
no
why is this here
void Update()
{
rb.velocity = velocity;
}```
also if you wanna keep adding speed you need a multiplier for moveSped
how do update velocity?
look at my example from my project
ok
vector2 in my case?
what does the method "reflect" do?
unity just 0s out the z
it "reflects" the direction incoming towards another direction
okk
in this case it would make sense the normal (face direction) of the collider
eg the paddle or wall
so it makes the ball bounce?
what's "movespeed"
a float
the starting speed?
basically
make sure to normalize the speed reflected first, so you can assign it another new speed
I realised that when I rotate the child object, the position changes
https://gyazo.com/113f12bc7b117d4cd2bd63c21778f214.gif
Is there some sort of formula that I have to apply to change the position when I'm rotating the child object?
on CollisionEnter(collider other)
if (other.CompareTag("player")
movespeed++
is your game 2d you need OnCollisionEnter2D
yeah but you still need to reflect
oh right
inside that
i need a separate script
no
oh i thought i needed to add the script to the objects, not to the ball, my bad
nah only ball needs script
since it keeps track of its own direction
can i use the position for the reset in the void start()?
as long as it runs ones. My ResetBall method runs everytime a goal trigger is hit
my goal trigger detects if ball entered trigger
but i can store the position into a variable
it calls ResetBall
initial position is only there for resetting the ball to where it was when point was scored
okk
i found this
but what's the red arrow?
its the normal
and how do i calculate it?
You get it from the collider in the collision parameter
the collision gives you Contacts
to where exactly the ball hit
Hey guys, If I am using other.CompareTag() to see if something hit the enemy in OnTriggerEnter2D on my Bullet script. I want to make that when the player gets a special hability now his bullet will hit one enemy and bounce to the enemy closer to that enemy. But all enemies use the same tag. Is that achievable? Would I just need to get the distance from the enemy hit to the closer one and redirect the bullet there?
I have two scripts, on that brings the player back to the beginning if he runs into a spike and one that makes him move. My problem is, that while the player is moving, he can't die, because the movement is occupied by the movement script. Can i somehow disable a script temporarily or make like a global boolean that gets set to true when he should be dead?
wdym by "the closer enemy"? You mean the enemy closest to the first enemy?
you can disable scripts easily, yes, with refToTheScript.enabled = false;
Player shoot the bullet. Bullet hit the enemy now the bullet needs to fly to the closest enemy to the first enemy hit
You can also have the movement script check something like if (isAlive) Move();
do an OverlapSphere or something, find all nearby emnemies, then just loop through and select the closest one
Good, But I haven't figuered out how to refernce the script of a parent correctly. I've seen something about parent. but I couldn't get it to work.
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("player"))
velocity += Vector2.one;
Vector2.Reflect(rb.velocity, Collision2D.GetContact());
}
which is the argument of collision2D.GetContact()?
well its an array. and you only need 1 contact
so how do we get 1 item out of an array?
array[index]
yes
GetContact returns items from an array, you need index.
well its a custom struct but thats out of the scope
why is it an array?
oh ok
hey, does someone knows why my mobilephone starts to get slow with this simple scene without code or anything else appart from the buildings and the fog?
actually, for nearest neighbor search overlapXX may fail, the only way is to loop through all colliders or considering using space partitioning to speed up
yes
Profile it
also not really code question
sure but in most gameplay scenarios you only want to be considering nearby objects anyway - i.e. this chain effect probably has a maximum range
Whats that? I have to say that there are no shadows, so it is no really calculating nothing...
more resources on How, links at the bottom of page
That is going to help me fixe the problem or is just gonna say me what's maybe happening?
both
not maybe though
its accurate
it's for android too?
btw if it starts getting progressively slower as you go chances are you keep spawning new pieces or something, and creating a lot of extra resoures
Ideally you would pool those spawned sections and recycle them as you pass
no, currently is just a scene that doesn't do nothing yet... i have not programmed anything
oh well something to keep in mind then if you plan on doing infinite type runner thing
you should still profile it and see whats using most resources
exactly, that was my idea, then i'll do some type of object pooling
But thanks for the advice
How do I reference the Script of a parent? The only thing I found is from 2019 and it didn't work and just referencing the component per public Component Moving; didn't work either.
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("player"))
rb.velocity += Vector2.one;
rb.velocity=Vector2.Reflect(rb.velocity, other.transform.position - transform.position);
}
what's the issue with this now
😭
dang.. I gotta run for a bit so Ill just spoon feed you my Collision real quick, ill be back in a few to explain it
private void OnCollisionEnter(Collision collision)
{
var newDir = Vector3.Reflect(moveDir, collision.GetContact(0).normal).normalized;
moveDir = newDir;
if(collision.collider.TryGetComponent(out PaddleMove _))
{
moveSpeed++;
}
moveDir *= moveSpeed;
rb.velocity = moveDir;
}```
other.tf.position-tf.position is not the normal of the surface
wdym "Didn't work". also don't use Component type, use the actual type of script not unity class
Okay so I have made a walk script but my character suddenly goes on his side when I start walking
this is before I have pressed any input from the script
if you wish to constrain the rotation of your object - feel free to do so on the Rigidbody
and this is after
private <ClassName> className;
void Awake(){
className = GetComponentInParent<ClassName>();
}```
I mean you could just do GetComponentInParent<Class> 🤔
thats only if 1 script on the parent ofc
or it grabs the first one 😛
why not just assign it manually
[SerializeField] private MyClass ayo;
I tried that but it didn't fix it
to prevent not assigning error lol
private void OnTriggerEnter(Collider other)
{
Debug.Log("Stufe 1");
if (other.gameObject.CompareTag("Death"))
{
Debug.Log("Stufe 2");
gameObject.transform.parent.GetComponent<movement>().enabled = false;
gameObject.transform.parent.position = Startposition;
gameObject.transform.parent.GetComponent<movement>().enabled = true;
}
}```
Why doesn't this move my character to the defined "Startposition"?
Show what you tried
this is the script
Again, show what you tried
As far as I can tell, you have not constrained your object's rotation in the Rigidbody inspector
oh yeah your RotateCharacter code is completely wrong
you are messing with quaternion x and y components 😱
you should NEVER be doing that
That's also a problem ^
!code for sharing code btw
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
what you need to do is:
moveDirection = Vector3.ProjectOnPlane(moveDirection, Vector3.up).normalized;
``` _before_ you feed it into the MoveCharacter and RotateCharacter functions
you also need to delete the lines:
targetRotation.x = 0; and the z one, they are completely incorrect.
then it will work well
(although you should also check that moveDirection != Vector3.zero before calling RotateCharacter)
btw, where and how exactly should I paste this? Bc I get errors if I paste it outside the public class and inside the public class.
you need to remove the '<>' from the first ClassName, but not the second
just referencing the component per public Component Moving; didn't work either.
Nonsense, of course it works
You wouldn't use Component though, you'd use the specific type you want
for example, if the script name is RandomScript
private RandomScript randomScript;
void Awake(){
randomScript = GetComponentInParent<RandomScript>();
}```
you mean randomScript =
a script may contain multiple classes
ur not referring to the script file
but the class inside
It would be a bit clearer if you were consistent with "<>"(where it should be kept and where it shouldn't). But thx for the help.
You're actually referring to a specific instance of the class
A "class" in C# is like a blueprint for objects. There can and usually are many objects of a given class in existence at runtime or edit time
thanks for the advice!
Cool
what's wrong with mine?
@rich adder, i ran the profiler and i get this... but i don't know how could this optimyze my code... Could you guide me a bit?
Hello, I have this code for rotating a tank turret towards where the player is looking. This works great as long as the root of the turret is on flat ground. However if the tank tilts the rotation is not linear anymore and it slows down before reaching the target rotation. I cant figure out how to fix this at all :/
that'll be because it's trying to rotate directly towards the player
but you're ignoring the X and Z euler angles
look at compare ?
i would suggest not messing with euler angles at all here
instead, you should project the player's position into the XZ plane of the turret, so that you aren't trying to look up or down at all
there are plenty of tutorials on how to use it properly, I dont have time to sit here and explain every detail. You should start by putting it in hierarchy view instead of timeline
Vector3 targetPos = target.position;
targetPos = Vector3.ProjectOnPlane(targetPos, transform.up);
Hi, I have an object that disappears when the player's view goes out of range.
The issue is that it doesn't reappear on time when the player reaches it and the players goes through it instead of colliding with it.
I can't figure out how to disable frustum culling for that object, please help.
This is one thing that I found on it but it doesn't seem to work:
_rend.allowOcclusionWhenDynamic = false;
If the turret is on level ground, this will throw out the Y component
this isn't quite right, though. I think you'd want to do target.position - transform.position, then project it
That will give you a look rotation that just spins around your Y Axis, without tilting up or down
then you can simply rotate towards it
I did that but it still doesn't work, do you know what is wrong with this script?
!code using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float moveSpeed = 5f; // Adjust this value to control the movement speed
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
// Get the input for movement
float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
// Calculate the movement direction based on the camera's forward and right vectors
Vector3 moveDirection = (Camera.main.transform.forward * verticalInput + Camera.main.transform.right * horizontalInput).normalized;
// Apply movement to the character
MoveCharacter(moveDirection);
// Rotate the character to face the movement direction without tilting
RotateCharacter(moveDirection);
moveDirection = Vector3.ProjectOnPlane(moveDirection, Vector3.up).normalized;
}
void MoveCharacter(Vector3 moveDirection)
{
moveDirection = Vector3.ProjectOnPlane(moveDirection, Vector3.up).normalized;
// Apply the movement to the rigidbody
rb.velocity = new Vector3(moveDirection.x * moveSpeed, rb.velocity.y, moveDirection.z * moveSpeed);
}
void RotateCharacter(Vector3 moveDirection)
{
moveDirection = Vector3.ProjectOnPlane(moveDirection, Vector3.up).normalized;
// Rotate the character to face the movement direction without tilting
if (moveDirection != Vector3.zero)
{
// Calculate the target rotation only around the Y-axis
Quaternion targetRotation = Quaternion.LookRotation(moveDirection, Vector3.up);
// Smoothly rotate the character towards the target rotation
transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, Time.deltaTime * 1000f);
}
}
}
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
private void OnTriggerEnter(Collider other)
{
Debug.Log("HI");
if (other.gameObject.CompareTag("Player"))
{
Player.transform.SetParent(other);
}
}```
This should reference the thing I collide with and then set as "Players" Parent, but I get an error that ```Argument 1: cannot convert from 'UnityEngine.Collider' to 'UnityEngine.Transform'```. I just want the Player to tick a moving Platform...
How can i best achieve that?
Thanks I will try this
it says that collider 2d has not a component "getcontact"
im having an issue with an on click. Im following a tutorial and havent missed a step. void Restart()
I set up the restart but the function WONT ACKNOWLEDGE RESTART. Its supposed to say Restart() under cancelinvoke()
Vector3 lookDir = target.position - transform.position;
lookDir = Vector3.ProjectOnPlane(lookDir, transform.up);
Quaternion goalRot = Quaternion.LookRotation(lookDir, transform.up);
because you can't use triggers to get contact
GetContact comes from Collision / Collision2D
I'm not confident on this yet, though. I'd need to go implement it to make sure I'm doing this right.
actually, i'm gonna go do that now :p
why are your walls / paddle triggers 🤔 @novel shoal
what do you mean?
make it public
If I understand Vector3.ProjectOnPlane() maybe transform.root.up instead of transform.up could be better?
The second argument should be the direction you want to ignore
oh ok
transform.root would be whatever transform is your greatest grandparent
THANK YOU!!!!
why are you using OnTriggerEnter2D instead of OnCollisionEnter2D
oh hey, nice: 2022.3.13f1 has an up-to-date Visual Studio Editor package
other is a Collider, SetParent needs a transform, so use other.transform
idk even the difference 😭
maybe i should watch more tutorials
thx
I understand it 😁
I'm trying to get my script to read the path points I have layed out but I keep getting this error and I don't know why
grid is null
okkk
I know but how do not have it null?
Is there an object of type Grid in the scene?
@wintry quarry do you know what is wrong with this? Because I have no clue
with collisionenter it says i cannot use comparetag
Yes
you can but you have to grab the collider/gameObject first
Try logging it after you find it and see
What do you mean?
assign the Grid to a class field instead of find it in run-time
Log the grid you found. See what it is
Like debug log?
you can simply solve it by this
yes
{
if (gameObject.CompareTag("player"))
rb.velocity += Vector2.one;
rb.velocity = Vector2.Reflect(rb.velocity, collision.GetContact(0).normal);
}
is this right @rich adder
Share the code properly and explain your issue better than "what's wrong with this"
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
no, look at my code and compare
also tag check is wrong..
Collision2D parameter holds the object you hit..
I already know which line is casuing the issue
Alright, sorry. My problem is that when I move around the character snaps to a sideways position, but I don't know why. I'd like to solve it.
you are making that not rb.velocity, but the direction
Well, yes, the error tells you
This checks the tag of the object attached to the script, not the other object
Im literally just storing it a vector3 so its easier to change but its the same as doing rb.velocity = value
so collider.comparetag?
And that's the right thing to do
No
collision.gameObject.CompareTag
Or
collision.collider.CompareTag
You need to go through the collision struct
Oh, do I do Debug.Log(gameObject.Grid)?
log the grid object you find
I asking to see if that was right
bump
but aren't moveDir and rb.velocity the same thing?
Does GameObject have a variable of type Grid
No.
moveDir is a variable you apply TO rb.velocity
That way if you want you can reference the moveDir outside of that method
It should since Grid is a object in the game
but here rb. velocity = moveDir
"Apply to rb.velocity"
Yeah, he applies it to it.
You CAN skip that step if you want
yoo @summer stump ;))
https://docs.unity3d.com/ScriptReference/GameObject.html
Is there a variable called .Grid on this class
right ? so im just storing it in a variable lol
Vector2
You are amazing, it works thanks so much i spent like 2 weeks on this I love you maaan
oh, nice; I was just fighting with getting the gun to elevate properly as well :p
getting the turret to rotate worked on the first try
No?
Okay, so what did you expect gameObject.Grid to get
Sorry, I was looking at the Debug scriptrefernce and seen this so I though it would work \
That will get you the .name property of this game object
okk
I understand now but then how should I do that
gameObject.<component>
transform is made intrinsic with gameobject because its used very frequently
gameObject.name / .tag also working
yes, any property of a GameObject can be used, by definition
i'm not sure what you're saying here
Just log grid
{
if (collision.gameObject.CompareTag("Player"))
rb.velocity += Vector2.one;
var newDir = Vector2.Reflect(rb.velocity, collision.GetContact(0).normal);
newDir = moveDir;
}
?
I see and it comes back Null
Then there is no object of that type in the scene when this runs
@rich adder
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Got it working. Here is an example of a tank with both a turning turret and an elevating gun.
Raising the gun is a little more complicated.
Thanks a lot man :D
In short, it finds the direction to the target, then rotates it so that it's facing forwards. Then it rotates towards that.
close but I think you should still do the ballmove speed multiplier like I said
so you should normalize new dir
Is visual studio the superior IDE?
I have gotten a JetBrains License
aren't you doing ball speed +=1?
they both do the exact same thing, jetbrains just has a few extra bells
I'm adding the speed variable so can keept rack of it
i guess i'll just watch a big physics tutorial in unity since i am not understanding so much
this has more to do with vector move than physics
it's kind of difficult for me to implement what i know about physics in unity with such a small knowledge
i did vectors but i don't know what a normal is
or, maybe i did it but it had a different name (i am italian)
you've seen the few images, is just the direction A wall is facing for example
so should I switch?
to jetbrains?
I can't make life decisions for you lol
a normal vector is a vector with magnitude 1.0- also called a DIRECTION vector. What great about normal vectors is: if you multiply them a by a single float sa X.. you know the length of your final vector will also be X.
use whichever one, they both do the same
I wouldnt call it a life decision
this is not correct
Perhaps you're thinking of how you "normalize" a vector
The names are confusing, yes.
okay thanks
no, I'm tyhinking of a normal vector
A normal vector is a vector that points straight out of a surface.
It's the direction the surface faces.
it's still kind of difficult and i feel bad for asking so much stuff from you that is something very easy
its fine , its good to learn
that is a USE of a normal vector. a normal vector has magntidue 1.0
normal vectors are generally normalized, yes, but you are not correct.
A vector with a length of one is a unit vector.
Normal Vector is not the same as a Normal_ized_ Vector. A Normal is Normalized, but not all Normalized vectors are Normals
imagine those squares are bendy walls @novel shoal the blue arrow is which way "they're facing"
which is the normal
ok
When you bounce something off a surface, you reflect its velocity using the normal vector.
and what does "normalizing" mean?
That is a separate concept.
turning the value to max of 1
To normalize a vector is to make its length exactly 1.
okk
"normalization" more generally means to make something consistent or uniform
For example, suppose I do this
Vector3 dir = rigidbody.transform.position - transform.position;
rigidbody.AddForce(dir, ForceMode.Impulse);
The further away I am from the target, the harder I shove it.
Where is game's screen resulation (1920x1080) data stored in a Unity exe build folder?
so i should just make newDir.normalize=moveDir
Vector3 dir = rigidbody.transform.position - transform.position;
dir = dir.normalized;
rigidbody.AddForce(dir, ForceMode.Impulse);
Now, no matter how far the target is, it gets shoved by a consistent amount.
newDir.Normalize()
or you can normalize the result of the whole Reflect which is what I did
Normalize a vector if all you care about is the direction
rather than both the direction and length
and if all you care about is the length, get the vector's .magnitude !
thx
vec = vec.normalized * vec.magnitude;
This code does nothing
(plus or minus floating point errors)
https://hastebin.com/share/etezogogeh.csharp gpt came up with this to sovle it
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
my ball is still not bouncing, i am giving up, sorry for bothering you
let me see current code
i tried my best but most likely this is just out of my range
i'll watch more tutorials before trying something made by me
is there a reason you're reflecting the ball in the collision method?
the ball is already gonna bounce
(even though it's not exactly made by me)
or is it not bouncing the way you want it to?
you never applied the new direction
it's not bouncing at all
@novel shoal
yes, you've calculated a new direction, then thrown it out
% and == comparison with Time.time... oof gpt
This is very unreliable cs if (Time.time % ShrinkInterval == 0)
It only works if Time.time is exactly 0, 60, 120, etc.
look at my code again cs private void OnCollisionEnter(Collision collision) { var newDir = Vector3.Reflect(moveDir, collision.GetContact(0).normal).normalized; moveDir = newDir; if(collision.collider.TryGetComponent(out PaddleMove _)) { moveSpeed++; } moveDir *= moveSpeed; rb.velocity = moveDir; } @novel shoal
you've also overwritten newDir with moveDir
i have to do rb.velocity=newDir?
this will reset the velocity to exactly 1
because you're normalizing newDir before assigning it to rb.velocity
remember: you normalize a vector if you don't care about its length
yes, you're still missing a velocity you can increase
you definitely care about this vector's length!
also, this is not correct
rb.velocity += Vector2.one;
This will add 1 to the X and Y velocities
^^ which is why I suggested a speed variable instead if you want speed increase
isn't that what i want?
that vector.one thing is useless
Do you want the ball to move 1 meter per second faster up and right every single time?
possibly slowing the ball down
I think you want it to increase its speed
if the ball is moving down and left, you will slow it down by increasing its X and Y velocity by 1 each
you see why I used a variable for speed 😏 @novel shoal
moveDir *= moveSpeed;
we normalize the direction, then multiply it by the move speed
i didn't understand what was that "*="
Since normalizing a vector makes its length exactly 1, multiplying that vector by moveSpeed gives you a vector whose length is moveSpeed
its the same as doing moveDir = moveDir * moveSpeed
so now the ball will have a speed of exactly moveSpeed
i have never used *= in python so i didn't know what was that
you should ask to clarify something when you don't understand it
i was already asking too much
i didn't want to annoy you
its fine, thats what this channel is for
not a unity specific thing per-se but yeah this is a simple math operator for multiply
but we short it when we dont want to repeat ourselves
so
myValue = myValue + 4;
same as
myValue += 4;
If you do not recognize an operator, you can look it up here https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/
i knew that with - and +, i just didnt know it existed for / and * since i had never used that before
Ahh gotcha well yeah its the same
so i have to normalize the vector after using it with the velocity?
no you normalize because you only care about direction
i don't understand what you mean by "using it with the velocity"
if you normalize afterwards, you're completely throwing out the speed
roughly the same as doing
x = 3;
x *= 4;
x = 1;
is there a reason to even store moveDir?
in my code I use it for other stuff but no they dont have to 😛
(in mycode is a backing field for public MoveDir get)
i have a question
@rich adder
what does the keyword "var" means? is it a short of "variable"? but in c# i have to declare the type of a variable before doing anything with it
yup but its a type that is inferred
if you did
var myValue = 0 the compiler think its a int
if you did var myValue = 0f now its a float
When you hover your mouse over var in your code editor all the secrets will be revealed
so depending on which value you assign it changes? so it's like in python when you don't assign a value
well you can only assign its type once and it has to be clear on what it is
it highlights Vector2
c# is not dynamically typed like js or maybe Py? i dont use py sorry
i don't know
Yep - so in that particular case var is equivalent to writing Vector2
it's just a shortcut for the type of whatever is on the right side of the = sign
so basically i can just type "moveDir" instead of "newDir" when i am storing it?
okk ty
you technically don't need moveDir I had that in mycode for keeping track where ball is from some other code
you can just assign the newDir to rb.velocity
My goodness chatGPT is useful as a beginner for niche problems
is this fine?
oh i forgot to fix it
if (collision.gameObject.CompareTag("Player"))
{
speed++;
}
var newDir = Vector2.Reflect(rb.velocity, collision.GetContact(0).normal);
newDir.Normalize();
newDir *= speed;
rb.velocity = newDir;```
😂
now it should be correct (i hope so)
now i got it
if i increase the value that i use to multiply the direction, the direction will increase
wdym
the newdir vector is increased every time it its something by the speed variable, which is always itself, except if it its an object whose tag is specified, because if it hits that object, the speed will increase
if it hits a barrier; 120
if it hits an object;121
1*20
1*21
it made the text in italics due to the *
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I'm following a simple top down rpg movement tutorial, and I'm trying to make sure I understand how everything is working so I can actually learn from the code. In the point of making a variable to define the move speed, the programmer gave it a value of 5f, I don't understand what the "f" stands for, if anything, as it doesn't give me any errors without it either.
this
float
It’s used to clarify what type you want.
It’s important if you want a decimal value
1.5 is a double, not a float
It’s a more precise type and it won’t automatically convert to float
1.5f is a flost
5 is an int. That can automatically convert to float
Hence why you didn’t need it
I sometimes add the f anyway
is this right now?
To learn more about literal values in C#: https://www.tutorialspoint.com/csharp/csharp_constants.htm
C Constants and Literals - The constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals. Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are also enumeration c
Oh that makes more sense, thanks
@rich adder
Have you tried it?
Have you checked if your code is even running?
it's assigned to the ball object if that's what you are asking
That’s not what I’m asking
Add a Debug.Log statement to the method and see if anything appears in the console
Is the Paddle tagged Player?
it should bounce regardless of the tag of the collider
No. Not using velocity
if the tag is player it only makes the speed higer
but it should bounce anyway
Oh I'm sorry. I see what you mean.
The code isn't behind the tag, gotcha
anyway yeah, both paddle have the tag "Player"
lol i should have started to study 2 hours ago
what's the issue with my code then?
idk how to solve it
wait is the bounce working and its just speed broken ?
can you send current code again
it shouldn't tho
cuz if it touches the paddle, it goes on until it touches the barrier
are you able to make a quick video of issue not sure I understand
ehh its fine this time sure, but you should learn how to use OBS https://obsproject.com/
oh right i have OBS
i completely forgot about it
i haven't been using it since some yt videos
literally 2 years ago
code looks fine . also might want to share the rigidbody settings you got
If I do StopAllCoroutines();
public IEnumerator TimerStart()
{
currTime = 1;
reviveTimer.fillAmount = currTime;
while (true)
{
currTime -= Time.deltaTime * 0.1f;
reviveTimer.fillAmount = currTime;
if (currTime <= 0f)
{
cancelButton.onClick.Invoke();
print("Invoke");
break;
}
yield return null;
}
}
my cancelButton gets invoked... why?
I would guess the two are not related. It's being called normally in the coroutine
Is StopAllCoroutine being called on the correct one that started it ?
possibly you are not calling StopAllCoroutines on the correct object
this is the whole code:
public class DeadTimerUIScript : MonoBehaviour
{
[SerializeField] private Image reviveTimer;
[SerializeField] private Button cancelButton;
private float currTime;
public IEnumerator TimerStart()
{
currTime = 1;
reviveTimer.fillAmount = currTime;
while (true)
{
currTime -= Time.deltaTime * 0.1f;
reviveTimer.fillAmount = currTime;
if (currTime <= 0f)
{
cancelButton.onClick.Invoke();
print("Invoke");
break;
}
yield return null;
}
}
public void TimerStop()
{
currTime = 0;
StopAllCoroutines();
}
}
and if I call TimerStop() it doesnt work
where did you sttart the coroutine from?
yeah you start it from somewhere else
I bet you start the coroutine on another object.
Seems like not in this object
from another script
it belongs to that other object
Each MonoBehaviour has a list of coroutines it's running
The reference you call StartCoroutine on matters A LOT
otherScript. StopAllCoroutines();
pay close attention
when you call StartCoroutine, you throw the IEnumerator into the list
make it mp4
its better to make a method in this class to StartCoroutine
instead of calling StartCoroutine from another class for this very reason tbh
so I should do
deadTimerUIScript.StopAllCoroutines();
in the object's script i started it?
no, this is identical.
how do i do it?
when you call StopAllCoroutines, you're telling the MonoBehaviour to throw out its list of coroutines.
it doesn't matter where you call it from
I'm guessing you have another class that looks like this
what do i have to do then to stop the timer and not getting the cancel invoked
this is the rigidbody
public void DoSomething() {
StartCoroutine(timerUI.TimerStart());
}
just do
public void TimerStart()
{
StartCoroutine(Whatever());
}
If you do this, then the coroutine is running on whatever object DoSomething is on
So yes -- do what navarone suggested
now the coroutine will be running on the DeadTimerUIScript object
and calling StopAllCoroutines on that object will stop it
in the OBS settings
it doesnt work
its still getting invoked
then show your code
I can't guess what you wrote
ah, good
the current transform moves towards and past the target how do I stop it at the target Point
make sure the pivot is accurate?
MoveTowards will not overshoot
If it only moves a little too far, then yeah, your pivot is off
so some other code would be responsible - or yes your object pivot is not correct
No it doesnt work, it doesnt get invoked instantly right now but after the time expires
public class DeadTimerUIScript : MonoBehaviour
{
[SerializeField] private Image reviveTimer;
[SerializeField] private Button cancelButton;
private float currTime;
public IEnumerator Timer()
{
currTime = 1;
reviveTimer.fillAmount = currTime;
while (true)
{
currTime -= Time.deltaTime * 0.1f;
reviveTimer.fillAmount = currTime;
if (currTime <= 0f)
{
cancelButton.onClick.Invoke();
print("Invoke");
break;
}
yield return null;
}
}
public void TimerStart()
{
StartCoroutine(Timer());
}
public void TimerStop()
{
StopCoroutine(Timer());
}
}
it kinda bounced on the paddle, but not on the barrier
That is incorrect.
that's not how StopCoroutine works
you're telling it to stop the return value of Timer()
If you had previous passed that exact value to StartCoroutine, it would indeed stop the coroutine
yeah the direction seems to be wrong.
var enumerator = Timer();
StartCoroutine(enumerator);
StopCoroutine(enumerator);
also is the Rotation on rigidbody locked by any chance ? @novel shoal
But this is just starting one coroutine and then stopping another one that hasn't even started yet
StartCoroutine(Timer());
StopCoroutine(Timer());
the z rotation
yeah dont lock it, try without it
If you want to stop that specific coroutine, save the IEnumerator that Timer() returns into a field, then pass it to StopCoroutine later
or you can just keep using StopAllCoroutines()
You can also store it in a Coroutine
okok, i locked it bc a tutorial told me to do so
in that case, you'd store the return value from StartCoroutine, yeah
still not bouncing
yeah got it now thank you!
You should get the coroutine ref when you create one so you can store that specific instance
@rich adder what?
nah nothing I thought It couldve been the wals for some reason, uh we have to Debug the direction
I am wondering if we're fighting the physics system here
how can we debug the direction?
not sure how, I have this exact code and it works flawlessly
but in 3D
Im wondering if maybe the in direction might need to be normalized
hm, even if the collision is really wasteful and loses most of the velocity, the tiny bit that's left should still be enough to make your code work
i don't get why it worked with the paddle here
we use Gizmos 🙂
gizmos?
I think something might be wrong with the returned normal
haha yeah thats why I try to extract things like direction into variable so i can use it to debug with gizmos (lines/arrows)
well, to clarify
you're probably about to use Debug.DrawLine
I guess that is technically a kind of gizmo?
I think of all the stuff in the Gizmos class when you say "gizmo", but that's fair
I use Debug.DrawLine a ton
super useful
it lets you draw a line in the scene view (and the game view, if you turn on gizmos there)
what the hell are gizmos?
things that help us visualize things
particularly invisible to human eye stuff
actually, is that a gizmo
okk

pivot is a gizmos for sure
so i need to use gizmo.drawline?
or Ray probably better
The collider visualizer is definitely a gizmo (:
remember that this would be Debug.DrawRay
oh, I see: there is also Gizmos.DrawLine/Gizmos.DrawRay
can one object have two tags?
The downside of that is that you have to do it in a specific gizmo-drawing method
no
just use Types
Debug.DrawLine and Debug.DrawRay can be used anywhere.
what are you trying to do?
I will look it up ty
that might be too vague of an answer lol
yeah just realized
i should use Gizmos.DrawLine(rb.transform,collider.transform)?
public class MyCoolClass : MonoBehavior
class is a type
Debug.DrawLine takes two positions and draws a line between them
i think navarone is suggesting identifying objects based on the components they have
instead of using a tag
so you'll look for a Door component instead of checking if the object has a tag named "Door"
yes Im bad at explain sorry
So suppose an object can both be damaged and collected
? but i need to differentiate between temporary things and temporary things are special
Explain your problem.
is there a method to check wheter an object has a said component?
it will have a Damageable component that handles being damaged and a Collectible component that tells you what you get when you pick it up
im gonna try your other code in a project real qucik too just in case. and no thats not what u want to debug
you can decide if something can be damaged by testing if it has a Damageable component
if it does, you can damage it. if it doesn't, you can't.
i got the plane and the obstacles as temporary objects, but the obstacles should be deleted with overlapsphere on revive but the plane should stay so i got all the objects from overlap sphere and now i want the temporary obstacles to be deleted but not the plane
use a layer mask to exclude certain objects from your physics queries
oh ok
let's rephrase this
yeah that sound good thank you
explain what happens in your game
no technical details; just tell me what the player sees
ok the player dies-> all obstacles in the area gets deleted so he can drive by
but not the ground
using UnityEngine;
public class TryGetComponentExample : MonoBehaviour
{
void Start()
{
if (TryGetComponent<HingeJoint>(out HingeJoint hinge))
{
hinge.useSpring = false;
}
}
}
what's <HingeJoint>(out HingeJoint hinge)?
<HingeJoint> is actually unecessary
unity has shite example
but it's the generic type parameter
but yeah what praetor said
HingeJoint is just the type of the component you want to check for. They are using HingeJoint as an example
this is using something called an out parameter.
It allows the method to assign one of your variables.
and (out hinge)?
You can just write if (TryGetComponent(out HingeJoint hinge))
So you actually hand that variable over and say "here, put something it"
If you already have a variable named hinge, you'd just write this
() is where method parameters go.
There is one parameter and it's out hinge
out just means it's an out parameter. An out parameter comes out of the call, sort of like an extra return value
TryGetComponent(out hinge);
You can also declare the variable at the same time that you call the method.
This is for convenience.
hinge is the object?
hinge is a reference to the component, if it exists
HingeJoint hinge;
TryGetComponent(out hinge);
okk
the method needs to give you two things:
- whether or not it worked
- the result
hingejoint is a component in 2D games
so it winds up using an out parameter for the latter
Okay, so I think using separate layers would be reasonable here
You could also just give every obstacle an Obstacle component.
yeah i used it and it works, thank you!
and then only destroy things that have an Obstacle on them
I fixed it!
wait what
you can make own components?
well, sure
and yes its to do with the physics and .velocity like Fen said i think
there's nothing really special here
where have you been writing your code if not on your own components?
note that every thing that derives from MonoBehaviour is defining a component
change
newDir = Vector2.Reflect(rb.velocity, collision.GetContact(0).normal);
to
newDir = Vector2.Reflect(newDir, collision.GetContact(0).normal);
@novel shoal
you mean scripts
MonoBehaviour is a specific kind of component
if (TryGetComponent(out Bar1) || TryGetComponent(out Bar2))
force++;
it says this is an error
"Scripts" is a really vague term that I don't like using.
your scripts are defining components. each class that derives from MonoBehaviour is a component like Fen pointed out
public class Foo : MonoBehaviour { }
This defines a class named Foo. Foo derives from MonoBehaviour.
whats the error ?
okk
what's the difference?
MonoBehaviour (any custom behaviour you've made) derives from Behaviour (any component that can be enabled and disabled), which derives from Component (any component)
bar1 is a type but it's used as a variable
yeah i mean those monobehaviour things and other stuff is my futures problem but i wont learn it today it seems very complex im happy with the skills of monobehaviour xD
by the time its taking the rb.velocity value , it is the value collided with the wall
I agree; a script (file) is more a Unity term . . .
so you're essentially reflecting the rb.velocity that collided with the wall
@novel shoal
I use the term "script" to refer to a script asset
is there a way i can get the value of the cube when it touches the red part? i already have it destroy itself but i cant figure out how to get the red part to get the value of the cube
you'll have a much easier time writing code and even understanding help provided here if you learn what you are doing instead of putting it off
the...value?
now I remember why I also stored velocity in a seperate value this way it isn't affected by the collision @novel shoal
hold up let me get the script
don't we want to reflect that speed?
that sounds rude haha yeah i will look into it
no we want to reflect the speed that it came in with before the collision
which is stored in newDir
before changing it
oh ok that kinda makes sense
this is the script for the cube and i cant figure out how to have the thing under it to get this value of this specific instance of the cube
it should work 💯 now
If the ball was stopping dead when it hit the wall, then you'd have no velocity at all
so yeah
but its hard to understand everything when youre self teaching because you cant learn new ways of doing things
why is that variable static?
so we are trying to reflect a speed that has just been negated because it collided with the collider?
Really, how so? They're encouraging you . . .
yup it made sense after it kinda just flopped
there is no value on the specific instance of the cube, because it is static!
i gotta fix this before lol
ohhhh
we are reflecting the original direction which is the uneffected velocity stored in newDir
Anyway, you need to:
- Detect that the red area has hit the cube
- Get the
BasicOreScriptobject from the object you hit - Get the value from the
BasicOreScriptobject
if we reflect the lost momentum we just flop down as you saw
yeah, i meant we were*
That value is applied to the class, not a specific instance . . .
still didnt say what the error is
also please do use brackets. even for one liners
so i have to mention the basicorescript in the hthing under it?
@rich adder
I do not know what you mean. I think you need to start by learning how to detect a collision.
Ah, good
yeah you need to store Bar inside a variable if you only want to out to a variable that already has the type
_ore is a GameObject
GameObject does not have a field called _worth
It will never have such a field
right now youre trying to pass a blueprint @novel shoal which is a class
so i have to get the script from the gameObject?
i am using them as much as i can
so i have to say Bar1=getcomponent<Bar1>?
no you assign bar a variable
and use the variable
(this should go into a thread too, btw)
yeah we are flooding chat make a thread @novel shoal
hey guys was able to destroy all enemies inside a list i have.. when i spawn them with instantiate I put them on a list and delete all .. it was working now I have this message here, and cant figure it out what could it be as I didnt change anything in the logic
void DestroyAllEnemies(){
foreach (Enemy enemy in _enemyList)
{
Destroy(enemy.gameObject);
}
foreach (BossOne bossOne in _BossOneList)
{
Destroy(bossOne.gameObject);
}
_BossOneList.Clear();
_enemyList.Clear();
}```
Something is likely still referencing something in one of those lists
I add to the list the ones that spawn, and I kil them and destroy, and after a whiule I want to delete all in the scene.. but I think it is trying to destroy also the ones I already killed
So, when you destroy them, you should remove them from the list
yeah, but how do I know which one is the one I killed to remove from the list?
save the reference to list when you spawn or something , then remove itself ondestroy
Hmm not sure if I understood..
isn't the thing that spawns it the same that keeps track ?
example, I am adding like that:
private IEnumerator SpawnPoison(float waitTime){
while (true){
float randomPositionX = Random.Range(-40, 41);
float randomPositionY = Random.Range(-23, 24);
float playerX = _player.transform.position.x;
float playerY = _player.transform.position.y;
Enemy poisonPos1 = Instantiate(_enemyPrefab, new Vector3((randomPositionX + playerX), (playerY + 41), 0), Quaternion.identity);
Enemy poisonPos2 = Instantiate(_enemyPrefab, new Vector3((randomPositionX + playerX), (playerY + -41), 0), Quaternion.identity);
poisonPos1.data = enemyTypeList[3];
poisonPos2.data = enemyTypeList[3];
_enemyList.Add(poisonPos1);
_enemyList.Add(poisonPos2);
Enemy poisonPos3 = Instantiate(_enemyPrefab, new Vector3((playerX + 56), (playerY + randomPositionY), 0), Quaternion.identity);
Enemy poisonPos4 = Instantiate(_enemyPrefab, new Vector3((playerX + -56), (playerY + randomPositionY), 0), Quaternion.identity);
poisonPos3.data = enemyTypeList[3];
poisonPos4.data = enemyTypeList[3];
_enemyList.Add(poisonPos3);
_enemyList.Add(poisonPos4);
yield return new WaitForSeconds(waitTime);
}
}```
you can also just make this tracker a singleton
ease of access
or just pass the script that has this list onto the object when you spawn it
like
poisonPos3.spawner = this
or something
hmm ok, I will try something. thank you !
you're welcome
Here is more info (better to use a method for this)
https://unity.huh.how/references/simple-dependency-injection
ok, thank you a lot it will take some time for me to achieve but as always I will get there.. thank you !
That is because that's likely where your camera is, so that is the position of the mouse cursor in world coordinates. If you want the Z value to be different, change it afterwards
why don't I have an option to make a volume game object?
whats a volume gameobject
as in Post Processing Volume?
if so do you have a render pipeline that supports it ?
In the tutorial I am watching they have volume objects
simple tutoriel: How to add custom skybox to your scene.
bastards stole my voice actor from another vid
anyway my question from before still applies
well then its wrong
the video says HDRP
so you need HDRP
URP and HDRP have built in Post Processing + Volume
Built-In "Normal" one doesn't
make a new project and select HDRP
can I make my existing project hdrp?
yeah but it takes a bit to configure it
also any material you have now has to be converted using the converter or they will be pink
if you dont have much done inside this project, I suggest you just start from template preconfigured for you
thanks!
I'm having an issue with a collider, can I talk with someone in DM's about it?
I hope I posted this in the right channel, sorry if I didn't
just post your question
Uh alright, I'm very new to Unity so sorry if it's a dumb question
I have this trash can which consists of the base and the lid which are children of an empty object
and I'm trying to use the void OnMouseDown() method in a script in the empty object
Is the script on one of collider
The script is a component of the TrashCan object
which one, i don't see it
Oh wait whoops, that was an older screenshot wait a second
The script did work when I used a simple rectangle with a box collider, but not when I put it in the empty object with the 2 children
yes because the signal doesn't go to children or parent
only the script with the collider clicked
Oh okay, can I make it so the signal does go through to children?
depends what you need it for there is many ways
For now I just want a simple Debug.Log message every time I click on the trash can
In the future I would like the lid to move up but I don't know if that changes anything
if you put a rigidbody and turn it kinematic the children can also be clicked
Does adding a rigidbody add gravity to the object?
not kinematic no
Alright, let me try real quick
Hey, I need some help. I am trying to use Editor scripts to create copies of a prefab and before making the copy access and modify some variables inside the prefab which I have linked to it using another script that I attached in unity. The code is like this
GameObject cellobj=AssetDatabase.LoadAssetAtPath<GameObject>("Assets/Prefabs/cell.prefab");
var attr = cellobj.GetComponent<cell_attr>();
Cell newCell=PrefabUtility.InstantiatePrefab(cellobj) as GameObject;
But it gives me an error
The type or namespace name 'cell_attr' could not be found (are you missing a using directive or an assembly reference?)
How do I access and modify cell_attr for this gameObject copy before instantiating the prefab.
It works now, thank you so much :)
what is cell_attr
I don't understand. Can you explain a bit.
I am using this inside an editor script btw
what is even the point of attr its not doing anything
I haven't included the whole code
I use this for checking some conditions etc
ok well regardless, your code error is telling you your type doesn't exist
GetComponent Gets Components
Is cell_attr a component
I will be back in 10 minutes need to take some screenshots
if its code please dont screenshot it 🙂
no the unity editor
Xd
So blank path is the prefab I am loading.
How can I get the array UpNeighbours which contains objects to other prefabs in an Editor script.
its inside Tile
Same way as any other variable in any other script. From a reference to the script
Yes but if I make a gameobject of blank tile can I get this
although isn't that a Unity class 🤔
It's a custom one with the same name
Ahh makes sense
You seem to be trying to make an editor tool before learning the very basics of Unity TBH @cunning heath
Sorry I am pretty new to Unity I also apologize for the slow response.
You might be better off starting with basic Unity tutorials first to learn the basics
Before doing something more advanced like editor tooling
!learn is a good place to start
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Thanks will check it
So the issue is Tile is a script attached to the prefab. I want to modify the values from the Tile script for a specific prefab
In another editor script