#💻┃code-beginner
1 messages · Page 132 of 1
That's strange
Generally what do people use for final projects? Rigidbody or CharacterController?
Souls like
I would say character controller because im guessing your player is just gonna have basic movement and a jump
Rigidbodies are physics based stuff like reacting to explosions, forces, stuff like that
But u can achieve the same stuff with a rigidbody
That's what I choose, but this Collider only when moving "scares" me
Try it, like i said it always seem to detect collisions whether or not i use Move()
Dont be afraid of anything test it and see
You eventually come up with ur own conclusions on which system is better
Let's say I'm calling Move on every frame. Then I'm always calling Move so there is necessary collisions right ?
Si^
Perfect then. Thanks!
Else if you aren't moving, you could always opt to set damaged flags and evaluate damage relative to those rather than when colliding.
Can you expand on this please? I've never heard of that
When you've hit the object and are required to receive damage per second/frame/whatnot, you'd set a flag and poll the damage to be done elsewhere.
What is a flag ? I don't find anything about it
A bool.
Not literally a flag
Ok thanks
I thought it was a Unity tool x)
haha no brother lol
Pls can somone help me!
Why on first scene draw monsters work fine but on next it doesent work! where is problem?
Here is script where everthing works fine
https://hatebin.com/vttnjjizti
And here where it dosent work
https://hatebin.com/nmhbmfshqz
But how can I know if I got hit without collision ?
The charaterController has a collider on it at all times
You seem to think that it only has a collider when u call Move()
Oh okay. I tought it was an alternative to the thing we talked about. My bad
Thats not the case
Your initial collision will have you informed that you've hit. If you haven't moved and the other object haven't moved, you're still hitting the object.
It's not feasible to develop a game with the console window hidden. You should always have the console window showing. Currently it has at least one error.
Looks like you have some errors to fix.
What should happen if no monster sprites are found? Why is it failing to load monster data? Look into the errors.
Yo can someone help me out? I have no idea how to fix this
it just says no valid target
when im tryna use my tilemap and I feel really stupid
Is this related to coding?
where's a more appropriate chat to put it
I just figured since its a beginner chat might be ok to put it here
its not related to coding, more just using this and I've never had this issue before when using tilemaps
Probably #💻┃unity-talk
Make sure to tell people how you're getting the error (where are you seeing the error and what are you trying to do ie how they would reproduce it)
!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 rly dont know how repair this...
so i created a custom namespace and am trying to access it; which one should i use preferably? I think they all work
libnsClass comp = gameObject.AddComponent<libnsClass>();
var comp = GetComponent<libns.libnsClass>();
var comp = GetComponent<libnsClass>();
Well guys I really need a quick help.... My mum is asking me what will the world do with game development
Pls answer
The first one. var shouldn't be used if the type isn't clearly apparent on the right side of the =
By "clearly apparent" I mean something like var x = new Thing();
thank you; i figured just because someone can write something the shortest way doesnt mean it is the best practice to
you dont need to type the namespace if there is no ambitious
eg you want to use System.Random and UnityEngine.Random at the same time then you must type the namespace, but using UnityEngine alone then not necessary
though you may need a using XX=namespace.XX since just typing XX may cause ambitious to compiler (again there is random class under system and unityengine), but we usually use the one under unityengine
what is this?
Exactly what it says
im not using a collab service, this is a new project
it only has a cube and a movement script
then i think you can just clear the console and ignore it?
Then uninstall the package
Yes that's the collab package
why would it automatically download?
hm, random question before I try to code this-
could I have a script that, for each transform in a list
renders a raycast to that transform, but if that raycast collides with a collider/gameobject with a specific tag, it will assign a variable to the coordinates where it collided, creating a point, and measure the distance between that point and its starting position, adding the amount to a different variable
then.
then, it would render another raycast betweeen the point where it collided and the transform in the list, up until it collides with something different, reaches that transform, or reaches the edge of the collider with that specific tag. In the case of the latter two, it would either assign the coordinates to a third variable, creating a second point, or use the transform as the second point. It would then measure the distance between the first and second point, multiply it, and then add to variable we added the distance before
My eyes glazed over after like step 5 but you can write whatever script you want
Debug.DrawRay
just asking if this specifically is possible/would work before I go and code it-
or DrawLine since you may have start and end point already
i don't know where the collab packege is im very confused
What about it wouldn't be possible? c# is a fully fledged programming language. You can write any behavior you want
Hi, for some reason the door doesnt play the open animation, can someone help?```cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerActions : MonoBehaviour
{
public Transform cam;
public float playerActivateDistance;
bool active = false;
private void Update(){
RaycastHit hit;
active = Physics.Raycast(cam.position, cam.TransformDirection(Vector3.forward), out hit, playerActivateDistance);
if(Input.GetKeyDown(KeyCode.E) && active == true){
if(hit.transform.GetComponent<Animator>() != null){
hit.transform.GetComponent<Animator>().SetTrigger("Activate");
}
}
}
}
Version Control
why is it called that lmao
Because that's what collaborate is
Version Control software
Like Git
i still have blue pluses
just asking, as, mostly due to my inexperience, I spent a lot of stuff working on code that just had no way to work in the end
and i still have the red warning about collab service
you already comes up with the step, try to translate them to code first
Sounds like a limitation of your programming skills
Everything is possible
There are no limits other than hardware limits and your skill
why is it still here
whats happening to me
im terrified
its a curse
why is it following me
im making a new project and if it follows me ill hurt someone
What?
The plus icon? Pretty sure it means that was added since your last Plastic SCM commit
but its giving me errors for a package i don't have
ok i change code and still have no idea where is problem...
Noones can help me?
Heres good script
https://hatebin.com/vttnjjizti
Heres doesnt working script
https://hatebin.com/fsqbsqqqsw
Anyone? pls... i know im dumb but its rly important for me
Very descriptive (sarcasm), post the error
It might be erroring because you don't have the package
i deleted the project, im remaking it now. thats why i didn't post the error just now
i did before, and that was then
it was a project with nothing but a cube and a movement script
got another strange issue with items existing but also not existing. It says that DisplayInventory itself does not exist, but if it's attached to the object like this how is that possible?
this is that thing again where I pick up an item and this should then change ui elements of an inventory display, but it beats me as to why it says it doesn't exist at all
The error says whatever refernce you had to it got destroyed
Is there any part of ur code that is destroying the instance of DisplayInventory?
nothing aside from switching the scenes unloading the gameobject as it should
Does any of ur code persist from scene to scene
as it's just a script attached to the object
Share a screenshot of the entire Inspector
none of the code should, only thing I assume would are my scriptable objects because they hold my inventoy
Share code
here ya go https://hastebin.com/share/pulacujoxo.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
hi, one little question, if i want a sound when an enemy die where i have to put all the things because i have the audio source on the enemy and i put it in the script of the enemy but the sound dont reproduce
so the audio source is being destroyed?
look
It creates an audio source for you and destroys it when it's done
damn there's something that handy built in? Cool, the more I know
is there a specific shader that should be applied to a material for minimal performance cost? is unlit texture the best available? is there any less performance costing?
This destroys the object in the same frame you create it.
An alternative to what Fen said is to use the second parameter of Destroy to delay it
Are you having problems with performance? I would tell you not to worry until your fps starts dropping too much
an unlit shader is relatively cheap, yes, but this seems like an odd question to ask
no i want the game to look like its really old
with minimal performance cost
i want it to be able to run on a samsung fridge
but whats the cheapest
Choose the shader that produces the visuals you want
You shouldn’t just do things “because optimization”
but my idea is "if its the most optimal, its probably the shittest"
and i want it the shittest
so i need to do it because optimisation
I do not understand
This idea is inaccurate
If you want a visual style, ask about creating that visual style
Use low resolution textures and low poly stuff?
If you want your game to look like Cruelty Squad, you don’t just pick the fastest shader you can find
shaders do not run on toasters
am doing that
That requires effort
I think an unlit shader and some really low quality textures is a good start, then crank your render settings down (if you're using URP in the scriptable object)
bro just haze out 50% pixels randomly with a shader and yes your purpose is fulfilled(reduce pixel depth)
smart...
you can set the texture's max size so you dont have to scale them down manually
is point filter the most optimal filtering?
Grab the render profiler and test things
yeah did that
should be
how do i "grab" the render profiler
Also, none of these are code questions.
Maybe #💥┃post-processing #archived-shaders and even #💻┃unity-talk would be better
i thought you were supposed to just do it here
Do what there? Set the graphics settings? You are supposed to do it there
yeah thats what i thought was meant
I just want to spawn an instance at my mouse, any help
Looks like initialMousePosition is invalid and has NaNs in it
is it possible to give the entire chunk of code
Where is that code? Is it ever running?
Show more of the code
AI Code?
no lol
comments feel a bit too perfect lol
also, getmousebuttondown and getmousebuttonup do not run in same frame
Most likely AI. There were in another server, starting out
so you are not actually setting the position before instantiating -> NaN
Or it's copy-pasted
cuh its not Ai
retrack mouseposition in input.mouseButtonUp()
it was working before with the Mouse Inputs as they are, I dont remember changing anything
wym by retrack?
did you not read bruh, this is literally the issue i can see
How to make smaller this white rectangle hitbox?
Default value for a vector is (0, 0, 0) not (NaN, NaN, NaN) so it's the mouse position that has a problem
just put the first red mark, before the second red mark in Input.getmousebuttonup()
But I want the Object to spawn where you click, not release
So I need to set initialmousepos when MouseButtonDown is triggered, no?
something might be resetting InitialmousePos then
Debug.Log(Intialmousepos) everywhere in update, to see where it goes NaN
you'll trace it quite easily if initialmousePos isn't changed anywhere
oh, seeing the error: you are doing "transform.position = ..." of the instantiated object somewhere then.
If you click on the error you'll get an extended description telling you where in the code it occured
Do that
click on the error, where does it say it originates from
it should be in blue colour, the topmost file name you see
on the "planet" object?
yes
check if velocity is nan with debug.log
Post the error it's way easier than guessing
It contains the file, and the line number directly
Divided by zero at some point
check the value of velocity with debug.log if it's NaN
it is
You get NaN when you divide by zero, if I remember correctly
probably some awkward calculation condition being fulfilled leading to a /0
This calculates how far you drag back
and then the planets velocity is set to it
But I dont know where it would divide by zero
did you debug.log velocity ?
just keep moving debug.log statement further back till you see it's not Nan, error identified
This is the only line where you divide. Either the r^2 is 0, or Scale is 0
that doesn't do what you think it does
Yeah that isn't doing what you think it does
Oh so I have to use math pow again
I don't think there's an integer power operator
But wouldnt that still not be zero?
But you can just use Mathf.Pow
a debugger would be very useful here
just look at the values yourself
well, avoid future problems i suppose
Yo,
This is my simple Script for my CameraMovement, which follows the player.
public class CameraMovement : MonoBehaviour
{
// Player
public Transform target;
public Vector3 offset;
void Update() {
transform.position = target.position + offset;
}
}
However, I would like the camera to stay behind the player even when the player is rotating (along the y-axis).
Any idea of how to do this? I suppose I need to use Transform.forward of the player (target)?
You have still a lot of XOR operations for Mass and G, keep in mind to fix those once the problem is fixed
Does pow work for negative exponents
But yes you can construct numbers like 10e-11f to avoid some Mathf.Pow calls
I'd check DistanceToObject.magnitude to see if it's not 0
Would anyone be willing to help me modify this script so that it randomly selects different monsters on a different scene from another folder? I would greatly appreciate your assistance.
https://hatebin.com/asnmzskzsb
ah it is
fml whys that happened
That would mean sunposition and planet position are the same
The two positions you used to construct the vector are identical
Look into cinemachine, which does all this for you.
You could instead then use the camera Y rotation to know where the player should point
If the script is on the sun, OR if you dragged yourself onto Suni in the Inspector
I named it Suni just so i could tell them apart
The script is on planet
so it must be sunposition thats messed up
And why are you multiplying the position by the scale in that first piece of code?
Im trying to make it to scale, so thats to convert pixel distance to KM
?
That offsets the position to somewhere else. It won't be at the center of the sun object anymore
oh i see what you mean
If you need to convert so you can display the values in the future, do so only when you display them
Units are usually expressed in meters, but you're free to interpret them as anything else
So if your sun is 200 "units" away, you can choose to display "200,000 KM" on your UI, by multiplying the value before displaying it
The equation for gravitational force irl uses a constant G, if I dont scale the distance wouldn't I have a different constant
I'm really confused. I have 3 raycasts shooting out of the player when performing a jump. One below for checking ground and two on the sides for detecting walls.
Yet for some reason I can spam jump even when not touching a wall? The raycast on the right is green indicating a hit but only up to a certain range too. Not sure how to debug this.
private bool IsTouchingWall()
{
// Check if the player is touching a wall
float extraWidth = 0.01f;
Vector2 raycastStartRight = playerCollider.bounds.center + new Vector3(playerCollider.bounds.extents.x, 0, 0);
Vector2 raycastEndRight =
raycastStartRight + Vector2.right * extraWidth;
Vector2 raycastStartLeft = playerCollider.bounds.center - new Vector3(playerCollider.bounds.extents.x, 0, 0);
Vector2 raycastEndLeft =
raycastStartLeft - Vector2.right * extraWidth;
// Drawing the lines for a duration of 2 seconds with a red color assuming it doesn't hit anything
Debug.DrawLine(raycastStartRight, raycastEndRight, Color.red, 2f);
Debug.DrawLine(raycastStartLeft, raycastEndLeft, Color.red, 2f);
RaycastHit2D raycastHitRight = Physics2D.Raycast(
raycastStartRight,
Vector2.right,
playerCollider.bounds.extents.x + extraWidth,
wallLayer
);
RaycastHit2D raycastHitLeft = Physics2D.Raycast(
raycastStartLeft,
-Vector2.right,
playerCollider.bounds.extents.x + extraWidth,
wallLayer
);
bool isTouchingWall = raycastHitRight.collider != null || raycastHitLeft.collider != null;
// If the rays hit a wall, draw green lines instead
if (isTouchingWall)
{
Debug.DrawLine(raycastStartRight, raycastEndRight, Color.green, 2f);
Debug.DrawLine(raycastStartLeft, raycastEndLeft, Color.green, 2f);
}
return isTouchingWall;
}
Before I was just using mass = 1, G = 1, and I was trying to convert it to scale
Which is where everything effed up lol
My walls are using the correct layer
Well yes of course, but you're going to hit a limitation very rapidly with these huge or very small numbers: floating-point precision issues
Basically the bigger your value is, the more inaccurate your calculations will get. Like 1_000_000_000f + 1f will be equal to 1_000_000_000f. That may be why they chose smaller numbers
one thing to note, though
Surely the relative error is the same though percentage wise
you can't "cheat" by just dividing all of your numbers by a constant
yeah
Relative error is consistent.
If you are using a new enough version of unity, you can turn on the Physics Debugger and look at the actual raycasts
how
I don't understand your wall detection raycasts. Those are really short
Hi, I want to ask question about delaying. Theres a shild gameobject(circle sprite) and it will be active when I press "P" button;
public GameObject shield;
int shield_hp = 3;
bool is_shield = false;
void Start() {
shield.SetActive(false);
}
void Update(){
if(Input.GetKeyDown(KeyCode.P)) {
is_shield = true;
shield_hp = 3;
shield.SetActive(true);
}
if(is_shield && shield_hp > 0)
shield.transform.position = new Vector3(transform.position.x,transform.position.y,1);
if(shield_hp == 0) {
is_shield = false;
shield.SetActive(false);
}
void OnTriggerEnter2D(Collider2D col) {
if(col.CompareTag("EnemyBulletTag")) {
GameObject explosion = Instantiate(ExplosionGO); //explosion animation
if(is_shield == false) {
Destroy(gameObject); //destroys player ship
}
else {
shield_hp--;
}
}
}
What kind of code can I write so that the shield closes again after 10 seconds after opening in the territory?
Thanks!
window > analysis > physics debug
I forget when raycast visualization was added, though
maybe 2022.3?
yeah they are for walljumping so I want to make sure the player is touching the wall
oh, I see the cause
scratch that.
RaycastHit2D raycastHitRight = Physics2D.Raycast(
raycastStartRight,
Vector2.right,
playerCollider.bounds.extents.x + extraWidth,
wallLayer
);
I forgot that argument 2 isn't the direction AND length
just the direction
and I see now that the raycast actually starts at the center of the player
the visualization is a little misleading
i thought it was starting at the edge of the player and going that extremely short distance
yeah it is?
let me slow down a little here :p
xD ok, It's weird cause when I try jump in some other part of the map, the raycast shows red like ^^
You should check what you're actually hitting with the raycasts
you could log the collider
but when im near a wall, for some reason sometimes it detects it even though the raycast doesnt touch it
no idea what im looking at
the Queries section would be the relevant one
doing a simple log says what its hitting
But like
how
oh
im an idiot
I think
hold on
How can i get data of gameobject that is colliding with a inheritor of the scipt?
I was drawing the raycast distance right, but I was not throwing it the right distance 🤦♂️ @swift crag
go to the declaration of G and hit shift-F12 with the name highlighted
this will show every reference to the field
Ah, that's why I thought it came from the center!
I saw that and figured it was going to the edge of the collider + the extra
well now that I have fully embarassed my self, I'll take my leave, thank you for trying to help @swift crag
do you manually call Update at any point?
it would have to be within the same class
The only thing in update is the debug logs
I use fixedupdate if that would also do whatever youre thinking of
but i never call it
use OnCollision methods
Start runs the frame after an object is instantiated
(for things you instantiate at runtime)
oh
FixedUpdate could nominally run before that happens
even still, the log remains as zero forever
maybe i should keep constants in a separate script and reference them?
can you share the entire script?
what if you just make G=1 in Awake()?
Are you getting any errors in your console from the Start method?
If an exception is thrown from Start, it might not get all the way to G = 1;
this
Yeah that's probably what is happening right now, there could be a NullReferenceException thrown
that's the default that'll be used for new objects
you're looking at the script asset itself
that only matters in the editor (when you Reset a component, I think)
you need to assign the reference on the actual in-scene planet
or, if you're instantiating a planet prefab, you need to assign it after you instantiate the planet
go to the gameobject in the scene and assign Sun there. I don't know when you would assign a variable in the script itself
Vector3 is 0,0,0 by default right
The suns actual position is 0,0,0 so i never realised something was wrong :v
I still dont understand where I'm meant to assign it though
Do you have a gameobject in your scene that has the Planet script attached to it?
whoever instantiates the planet should assign the reference
you probably dragged the sun prefab into the field on the script asset
which would be irrelevant anyway
ok how do you spawn the planets? You have a prefab for planet right?
Yeah
Ok go to the prefab for planet
Script called MouseClick that checks for input and instantiates planet
And drag in your Planet script into it
Now all planet prefabs spawned will have that script
yes
and now drag your Sun prefab/gameobject into there
yeah
I have never dragged things into the script itself in Unity. I don't know what that does tbh
np <3
How can i check if player is lower than Y = -10 ?
you need to access it's transform component and check if transfrom.position.y < -10
alright, thank you
please keep in mind about Local and Global position
Global position checks the position relative to the WORLDS oigin. but local position check relative to a parent if the gameobject is a child of some parent
transform.localPosition.y is what you want for local position
what i wrote the first time
transfrom.position.y < -10
Wait would it be easier to make the Sun a parent of all planets and find the distance between them this way?
Depends what you are going for. If the planets orbit the sun like in real life for example and you want to check their distance from the sun then yeah you can use local position for this
i might just not risk changing it, its working now 
you wouldnt need to get the global position of the sun and compare it with the global position of the planet for instance
Oh right, and one more question, i just want to make a system that will teleport the player to 0,0,0 after he falls, how do i refer to his position? Just transform.position doesnt work.
how do you have the player referenced in the script?
He isnt referenced, because this script is attached to him
so then transform.position would work just fine
what do you mean "doesn't work"?
"doesn't work" is not helpful; you wouldn't be asking if it was working properly!
You would have to do something like transform.position = new Vector2 or Vector3
I think
If your player has a Rigidbody on it, you'll need to set the rigidbody's position, instead of directly setting the position on the Transform
and if you're using a CharacterController, you need to disable it before setting your position (and then re-enable it afterward)
private void AntiFall()
{
if(transform.position.y > MinHeight.y)
{
gameObject.transform.position = StartPoint;
}
}
I made this and this doesnt show any errors , but as soon as i start the game it locks player on 0,0,0
What is wrong now?
you have your condition backwards
this sets your position when you're above the min height
I have two gameObjects with colliders and isTrigger is switched on
The OnTriggerEnter event is only working on one of them
Anyone know why?
Almost the same functions
"almost" isn't enough, so show your code
we'll also want to see the inspectors for the objects
using System.Collections.Generic;
using UnityEngine;
public class plateController2 : MonoBehaviour
{
private Animator anim;
void OnTriggerEnter(Collider obj){
Debug.Log("On Plate 2");
anim.SetBool("isSteppedOn", true);
}
void Start()
{
anim = (Animator)FindObjectsOfType<Animator>()[0];
// Debug.log(anim.GetBehaviours());
}
// Update is called once per frame
void Update()
{
}
}```
instead of checking your player height for another height. You would typically use a barrier game object. And then check if your player collides with that barrier or void zone to spawn the player back to where needed. Because if you even want to move that out of bounds area in your game, you won't be able to since you are checking for a specific Y point
post code like 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.
the latter option -- inline code
Yeah your right
I have also thought about this, but didnt think its a great idea
The inspector
Is this the one that works?
Nope, this is the one that doesnt
let's see the other one
The inspector for the one that works
using System.Collections.Generic;
using UnityEngine;
public class plateController : MonoBehaviour
{
private Animator anim;
void OnTriggerEnter(Collider obj){
Debug.Log("On Plate 1");
anim.SetBool("isSteppedOn", false);
}
void Start()
{
anim = (Animator)FindObjectsOfType<Animator>()[0];
// Debug.log(anim.GetBehaviours());
}
// Update is called once per frame
void Update()
{
}
}
Code
Nope
hello!
myUIGroup.alpha += multiplier * Mathf.Min(Time.unscaledDeltaTime, Time.maximumDeltaTime);
is this the best way to use the eqquivalent of deltatime when timescale is 0?
why do you have two classes that have the exact same code in them?
That trigger event isn't triggering
I noticed that your code is using FindObjectsOfType<Animator>() to grab an Animator from...somewhere, which is weird
yeah this is just some demo project, Not really a game
One of the two objects in a trigger overlap must have a Rigidbody on it. Does the player have one?
also, peek at "Layer Overrides" on the colliders to make sure there's nothing funny in there
Its 0, Nothing, Nothing
is that not allowed?
it's just weird
None of them have rigidBody, but let me check
https://unity.huh.how/physics-messages has a checklist
seems odd that one of the two would be working
Im trying your method, but this ```cs
private void OnCollisionEnter(Collision other){
if (other = player)
}
Shows a error called that i cant convert unityengine.Collision to unityengine.GameObject, how do i fix this?
other is a Collision, player is a Gameobject. access the collision's gameobject attribute or access the players collider to check if they are equal.
Also the actual problem is that you are using = instead of ==
its trying to set other to player
Why are you trying to change the value of other inside a condition
nah he just mistyped the == check
Riight, sorry, its alright now
Tbh im new to coding and never knew a difference between = and ==, but now i know. So = sets first thing to the second one but == compares?
yes
alright, thank you
is the start method only fired the first time something loads? if you switch scenes and go back is start called again or no?
I remember seeing you helping out like 2 years ago when I started using Unity, so cool that you're still here
The answer is yes to both questions!
depends on how you switch scenes
When you load a scene, all of the objects in the scene are loaded in
assuming you're not additively loading several scenes at once
right
The same thing, this guy is sitting here forever haha
the old scene is unloaded
that's making me extra confused now X/
how did u learn so much in 2 years
2 years is a long time and I still don't know shit xD
Start runs once on your MonoBehaviours.
but if you unload a scene, all of the things in it are destroyed
when you load it again, those are new objects
funny lol
cause to test stuff I added this to clear the items displayed. I go from one scene to another, then back to this scene, itemsdisplayed is set to 0. But as i've shown before it should add all the pairs to the dictionary after starting up again
please share the whole script in a paste site
I don't want to look at screenshots
fair enough
got it above alreadym lemme find it
https://hastebin.com/share/pulacujoxo.csharp here we are
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
something wacky is going on that I must not be understanding correctly because it isn't doing what I expect when it loads up
this is redundant, by the way
the for loop will execute zero times if the count is zero
does Inventory do some work in its own Start method?
if so, you may be relying on the exact order in which they start
inventory itself doesn't use the start method at all
what I assume is happening is it's creating the itemsDisplayed dictionary on first start, and when it goes back to the scene it uses that one instead of the new one it creates, which doesn't make sense
only if a reference to the dictionary has been handed to someone else
(and that wouldn't affect DisplayInventory)
it sounds to me like your inventory is empty when you come back to this scene
or is that third screenshot from a debugging session?
the third was just supposed to be an overview of what that method does before I pasted the whole thing.
check if you're actually running that loop at all
definitely is
wait, does Inventory survive the scene load?
you aren't unsubscribing from inventory.onItemInventoryAdded
I bet you're seeing the result of the inventory invoking the old DisplayInventory's UpdateDisplay method
that's perfectly legal; destroyed unity objects still exist
inventory itself is a scriptable object. so from my knowledge it should't unload
it won't unload if the new scene has references to it, at least
scriptable objects can unload if they're left with no references
(putting it in a static field would also suffice)
unsubscribe in OnDestroy and you should no longer see the weird empty dictionary
all the scenes have some kind of reference to it, so I assume it wouldn't be unloaded
will give this a try. if it works then that'll be 3 days of painful turmoil resolved
Is there a way to make my player fall faster without changing gravity or his mass?
I'm doing a fair bit of stuff with events. You have to make sure you aren't leaving "dangling" subscribers around
I guess it makes sense conceptually though, since inventory is now complaining about not having a displayinventory, could be that the inventory remains persistent throughout but it's the event that's gone
increase his -y velocity in FixedUpdate
im having an issue with inputs, ive been following a tutorial on a first person controller to use as a base for other things and for some reason everything but the jump works
i beleive this is everything including the code for jumping, but theres no said errors so im left trying to find it myself
moment of truth 🤞
You need to configure your !IDE before proceeding
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
is that why my text has less colors than others?
Yep
ah
also @vernal plume I see no evidence whatsoever that you have tried to debug this code
This doesnt seem like a good solution...
how else would you suggest?
I dont know, i think i should change my movement system, i needed to change drag force to 5 and it made me fall much slower, but also not stick to walls and slide all around the ground
I need to find movement system that can use drag force equal to 0 and make me not stick to walls or slide
think about it irl, if something is falling and you want it to fall faster you increase it's downwards velocity by pushing it down,, or not?
oh my, this actually worked! makes sense thinking about it now but I wouldn't have spotted it. Events are still new to me
Mass doesnt affect the falling speed
Read what i just said
The rule of thumb: if the thing you subscribe to outlives you, you need to explicitly unsubscribe
Idk if it does or not, but thank you
if you don't want your object to stick to walls then make a new physics material 2d and drag that into the rigidbody of your gameobject
noted, I'll be sure to keep that in mind in the future
it seems to have worked, couple seconds after loading the colors popped up
if you want the player to fall faster, increse its gravity scale in the rigidbody
It’s literally what you asked for
thanks ever so much for bearing with me X/
If you want to make the player fall faster, you need to make the player…fall faster
Good. Errors should now be underlined red in the code, and you should have a list that appears when you type code
my old ui slot removal method should work now, you remember the whole 'value is null thing'? I reckon this would have fixed it
Thank you!!
I forgot to mention to make the frction of the material 0, but I guess you figured it out
yea im not finding any errors in spelling or missing characters
Yep you now need to debug why it's not jumping
Whether the stuff on lines 70-75 is executing, etc.
As they're guarded by an if statement with 3 conditions, if one of them is false, nothing will execute. You might want to print out each condition with Debug.Log() and check that they're all true
Or remove the conditions one by one until it starts working - then the last condition you removed was the faulty one
when resizing a ui element like this, is there a keybind to just drag the bottom edge up and the top one moves down to mirror it?
alt
i think
click, then hold alt and drag
yeah its alt
make sure you click on the edge first, then hold alt and move your mouse
@hidden sleet
that's neat
Do you guys create handmade animations for every character? Isn't that a lot of work?
hold alt+shift to proportional resizing from center of object
yup
I mean there are a lot of ways to animate
but yeah, for 2d you make a sprite sheet of animations
or you make it use bones and animate the bones
but yeah its a lot of work
could also use procedural animations
it's fun spotting their uses in games once you learn about them
I have such a problem, created a territory unity 3d, but when I want to add more height, nothing comes out and it does not change (Same problem with downsizing)
i figured it out while scrolling through the comments of the tutorial
the creator forgot to show themselves adding readyToJump = true; to start() so by default the variable was set to false
Thanks for the help with the IDE thing cuz I probably wouldn't have figured it out till much later
what is the different between the yellow and grey box when resizing ui panels?
I'm messing with some very simple scripts and created a game object with a RifleStats script that has some basic values like minimum damage, maximum damage, and weight. It has a 'hasScope' bool set to false. My understanding is that I can have a 'RifleScope' script that sets that 'hasScope' bool on the Rifle itself to true, and gives a +1 to damage or whatever.
Am I understanding that right?
You could use that field when deciding how much damage the rifle should deal, yes
float damage = rifleStats.damage;
if (rifleStats.hasScope)
damage *= 1.25f;
for example
That is cleaner than how I had it. Cheers.
How exactly do you make it so that adding the Scope script to the gameobject satisfies that condition?
I cant seem to get this to register clicks. It worked once but now it wont register.
the event system is new input system one with default input actions
do you have an event system in the scene? does your canvas have a graphics raycaster? does the button have some sort of graphic that that graphics raycaster can target? is there anything blocking the button?
As I mentioned, the rifle has a bool to indicate whether or not it has a scope, and I tried to have another script that set that bool to true thinking that would trigger the damage modification, but I got a 'An object reference is required for the non-static field, method, or property 'member'' error. Is that related to instantiation?
does it need an image or sprite renderer? I just want it to be an invisible button. Should I even use the button component if I want it to be invisible?
https://docs.unity3d.com/Packages/com.unity.ugui@1.0/manual/script-GraphicRaycaster.html
The Raycaster looks at all Graphics on the canvas and determines if any of them have been hit.
yes, it needs some sort of image. you can probably just set the image's alpha to 0 if you want it to be invisible though
Hey guys
Short question: How do I detect whether if an scene has been loaded because the application started or because another scene loaded it?
Long question: I have opening and closing animations for scene transitions. The main scene is the Main Menu, which is the first scene to be loaded when the game starts, but you can also reach it by returning from the game. In order for animations to work properly I need to check if the Main Menu scene was loaded because the application started or if it was loaded by returning from the game scene
okay thanks, I added a image, but now it only wants to register the most recent version of the button I make. I have 3 identical buttons duplicated. It will only register clicks on the one I made most recently. Im very confused by that.
are they overlapping
the button does not have a hitbox. the image is its "hitbox"
I have a problem with import from blender to unity.No matter what i choose in Forward and Up options, my crown is always rotated 90 degrees in unity, what causes that?
heres the hitbox of the image so I dont think so
this is a code channel. maybe ask in #🔀┃art-asset-workflow or some other related channel
oh right
how do I hold the instantiated gameObject as a variable? I need to run a few functions on it before I "let it go" and move on to instantiating the next cell
var myObject = Instantiate()
well at this point it is not a code issue if you have confirmed only the latest button is printing anything when you click it so post your setup in #📲┃ui-ux for someone to help you
thank you
you also need to get your !IDE configured
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
What tells you that?
the fact that you have no syntax highlighting for a method from the inherited class
in "RaycastHit2D hit = Physics2D.Raycast(transform.position, t.position);"
what kind of variable is hit?
It’s right there (:
you do realize that a variable declaration includes its type. RaycastHit2D hit = is declaring a variable called hit of type RaycastHit2D
also, a position doesn't often make sense to be used as a direction, and that logic is likely incorrect
indeed
Hello, why when my character is colliding with the ladder, even though he is on the ground, he is unable to jump? And how can I fix this? The code: (sorry for the english, I'm using google translator)
does this look correct now?
yes
When you jump, you use AddForce, but when you climb, you're setting the velocity. Assigning the velocity will override the force added when jumping, so the jumping never occurs . . .
oh yes, that actually makes sense, thank you
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlatformAttach : MonoBehaviour
{
public GameObject player;
private void OnTriggerEnter(Collider other)
{
if (other.tag == "Rigid")
{
other.transform.parent = transform;
}
}
private void OnTriggerExit(Collider other)
{
if (other.tag == "Rigid")
{
other.transform.parent = null;
}
}
}
I've created this code to make player stay on my moving platform, i made it move by using animator with "Animate Physics" Everything seems okay till the platform starts moving. Meaning that i cant move on it, my ability to move my player comes back after it stops. Whys that?
is there any issues/buggy-ness with setting the camera as a child of the player?
If you're having issues or bugs with that then it's because of your code, if that's what you're asking
ok, thank you. Just thought I heard somewhere that it was bad practice to put the camera as a child of the player to keep it on them
How do I duplicate an animation clip? I have to make another one pretty similar to an animation I have but I don't want to do the whole thing again
Forget it, just had to duplicate the file
I'm trying to create a grid of squares on a canvas using this function and I can't figure out why it's not working. parent.transform sets the cells, which are image objects, to be children of the canvas correctly but the positioning is always offscreen and theres' always a different of like .1 instead of a full hundred
the node holding the script is a child of the same canvas, and is at 0, 0, 0
are you sure you don't want localPosition?
also, don't you want to multiply, instead of add? The difference would be 1 with the current code
Thank you yeah that was part of the problem,
and yeah that fixed both problems actually thank you very much
Do you have an .FBX file?
If so, you can create as many animation clips out of it as you want
oh no, I was talking about 2D animations
like changing position and so
yo idk if this is the place to ask, but does anyone know how to get the word autofill to work with all the unity commands in vs code
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
I have it working with half of them but some like SetBool just dont autofill
but stuff like update and vector3 autofill
if you have followed all of the instructions for getting it configured and regenerating project files doesn't fix it, then consider switching to a real IDE that is less likely to just not work
note that it's likely you have not followed all of the instructions
Many people use !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
im having a massive brain fog how do i get the angle of a object that a raycast has hit
The angle from what? Like what angle away from transform.forward?
nah more or less the slope of a object so when i instantiate something it has the same rotation
Ah, check the normal of the ground
I did which is where and still not doing what i was expecting it stays the same rotation
show code
public void GetPositionAndRotationOnClick()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
Vector3 targetPosition = Vector3.zero;
Vector3 targetRotation = Vector3.zero;
if (Physics.Raycast(ray, out hit, Mathf.Infinity, walkableLayer))
{
targetPosition = hit.point;
targetRotation.x = hit.transform.eulerAngles.x;
targetRotation.y = hit.transform.eulerAngles.y;
targetRotation.z = hit.transform.eulerAngles.z;
}
navMeshAgent.SetDestination(targetPosition);
ClickVFXManager.instance.InstaniateClickVFX(targetPosition, targetRotation);
}
I even tried this second method right here which doesn't seem to produce any results either
I don't see the normal in it
What is walkableLayer
Just the ground basically
What is it literally
i have a plane with the layer
Is it a LayerMask?
well, Aethenosity is correct, you're not using the normal, you're just using the transform of the thing you hit
which isn't guaranteed to be rotated at all
i tried using the normal and didnt produce any results ill show you what i had before
public void GetPositionAndRotationOnClick()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
Vector3 targetPosition = Vector3.zero;
Vector3 targetRotation = Vector3.zero;
if (Physics.Raycast(ray, out hit, Mathf.Infinity, walkableLayer))
{
targetPosition = hit.point;
targetPosition = hit.normal;
}
navMeshAgent.SetDestination(targetPosition);
ClickVFXManager.instance.InstaniateClickVFX(targetPosition, targetRotation);
}
This is what i had before
endless im missing something that i just forgot im currently lost on this matter
and i know the targetPosition is the wrong thing
You are seetting targetPosition to the normal, which immediately overrides the position, and your rotation is always 0
didnt mean to do that
A normal is also a direction not a rotation, so you can't directly use it as a eulerAngle
So lets say i want to spawn some rocks or something for example, and the terrain has hills and such how would i get the rock to match the angle of the slope, thats what im trying to achieve and i dont know if im going about this correctly
transform.up = someNormalVector will align a transform's up vector with the normal vector
public void InstaniateClickVFX(Vector3 instaniatePosition, Vector3 objectNormal)
{
GameObject instaniatedEffect = Instantiate(clickVFX);
instaniatePosition.y += 0.001f;
instaniatedEffect.transform.position = instaniatePosition;
instaniatedEffect.transform.up = objectNormal;
}
could it be something im doing with the instaniation then
is there a difference between Input.GetAxis("Mouse X") and Input.GetAxis("Horizontal")?
I believe the Horiziontal supports controller also vs Mouse X
but they basically take the same value?
Same thing Horizontal has support for controllers if im remembering correct
or no the Horizontal is for aswd
Horizontal is left and right arrows, and a/d
Mouse X is the mouse moving left and right
All these axes can be seen in the input manager window
You can also make your own
same with vertical
Show what the object spawns like; selected in the scene with the tool handle rotation set to Pivot
Can I show an image of a gameobject in the inspector with custom editor window?
create a custom editor script that utilizes the EditorGUILayout and EditorGUI classes to display a preview image
But yes you can
Oh the partical system doesnt rotate with the gameobject
i got to rotate the partical directly
That's what I'd expect to see; the up vector is aligned to the normal
Not related to your issue right now but tip for later, you can set your particle system's Stop Action (in main module) to "Destroy", so the object is destroyed when the particle system has finished rendering. That avoids making a script that destroys the object after a set amount of time
Sweet appreciate
If you plan to use object pooling you can also make it execute a method instead
I knew there was something going on appreciate you pushing me in that direction definitly had me confused
Which is definitly be a better option
Need some help. I have a working interactable UI that works on first start up of the game but if i stop and start the game again it stops working completly?
You'd probably want to provide further context (code, hierarchy, etc)
is it possible to desactivate rigidbody?
or just the kinematic
with a script
i tried and it did not work
just making it kinematic should be fine, depends on your use case
deactivate it in what sense
i wanna make the player be ragdoll when dead
what did you try, show the code or setup
That won't do anything noticeable on its own
This is my issue, ive honestly never had this problem before so im stumpped. My code for showing includes booleans that are all set on start and the ui is set active to false on start
@clear seal Without forces acting on it, there will be nothing to ragdoll it
BUT, that WILL allow forces to act on it
This should give you an error, where are you assigning the rb
Don't crop images
the console after runtime
the first log is the musket raycast
when it hit
something
Yeah, so that error is for the line you showed earlier...
And that needs to be fixed obviously, before your code will work
Rb is null
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Serialize/publicize it and set the reference from the inspector or acquire the component in awake/start.
that's prob why
[SerializeField] Rigidbody rb; then drag and drop the rb in the editor window
i alr did
thx
any idea on why this is happening?
can i see your code
whole code snippet here?
ok you can remove it i got it copied
cheers
Post long code with links as shown here
!code 👇
Not sure why they said remove it, maybe I misunderstood, but everyone being able to see the code means everyone can help. Always best to keep it up
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
You dont mind if i just revise this do you
go ahead
ill repost it in one
what would be the time.delta of the first frame if its based on the last frame
print it and find out
ok
How do I assign gameobject layer to layermask set in the inspector?
[SerializeField]
private LayerMask tileLayer;
...
gameObject.layer = tileLayer;
the gameObject.layer is just a number from 0 to 32, it is not a bitmask like a LayerMask is
what? no it doesn't
GetMask
yes and GetMask returns a bitmask, not the index number
It doesn't make sense to convert it
What are you trying to achieve?
Trying to set the layer
Layermask is kinda like a list of layers
To layermask
LayerMask.LayerToName?
You cannot. That makes no sense
@nova swiftNo
And that is an xy problem. What are you trying to achieve by doing that
Because gameobjects can only have one layer
LayerMask.NameToLayer will give you the number you need no?
Then don't use Layermask
Use an int
https://gdl.space/sutedokona.cs You can try this i just restructured
the code also all you interactables need to have a set layer
@summer stumpThat is less userfriendly and I don't get the layer dropdown
You can set the layer directly at the top.
But either way, it is not possible to do what you're asking in a smart way
So I can't convert LayerMask selected in inspector to the layer int?
you could use an asset like NaughtyAttributes and you can use a string variable with an attribute to get a layer dropdown
https://unity.huh.how/bitmasks
this is what is happening when you use a LayerMask
oh yeah I forgot naughty has that
What a hassle
otherwise you can do an onvalidate method
You could probably do it, but it would be dumb to do so really
Look at bitshifting
what is the actual point of what you are trying to do? perhaps a better/easier to work with solution can be suggested based on the actual problem you are trying to solve
There is also the option of just creating an enum for your layers with the correct values assigned so that you can use that to pick a layer in the inspector
I just want the layer dropdown and assign the selection when I Instantiate a gameobject instead of hardcoding numbers
why not just set the layer on the prefab and not worry about assigning it manually via code?
Make a prefab then? Set the layer there?
Well because I set ignore raycast layer when I spawn it because it sits on the cursor, and when I place it I use CheckBox and it finds itself, I need to rearrange all the code I guess
How to get a pixel's depth or z position for a Unity 2D shader? For something like this:
fixed4 Frag(vert2frag i) : SV_Target
{
float4 distortedGrabPosition = i.grabPos;
float distanceToCenter = distance(i.uv, 0.5);
fixed4 screenBehind = tex2Dproj(_GrabTexture, UNITY_PROJ_COORD(distortedGrabPosition));
screenBehind *= i.color;
if(i.uv.x < 0.5f) //Need to get depth/z position of a pixel/object
{
screenBehind.rgb = 0;
}
return screenBehind;
}
alright thank you
I think you need to explain your situation further.
So if I set layer on the GO in prefab as "Tile", and I instantiate on cursor, when I try to place the obj I check if coordinate Physics.Checkbox has Tile and it finds itself on the cursor
I can drag it around on cursor
so disable its collider until it is placed
There is sadly no type that represents a layer other than an int, and no attribute that would do it.
Here's an attribute and drawer that does it: https://gdl.space/jiraliyovu.cs (ah, I forgot one part: https://gdl.space/nuvevadiho.cs)
Just add [Layer] above an int (+the correct namespace)
But in this case it does seem unnecessary and the other solutions seem more sensible
Cheers ill give this a look rn
Hopefully this resolves that weird bug you were having
@slender nymphThanks that works lol
So I have been using Physics.Raycast with a LayerMask from inspector this whole time, and it seems to have been working, why is that?
Works on first play but any play after doesnt work so confused...
Still doing the same thing aye
Thats a beautiful way to structure code tho ill defintley be using that more to save lines
because physics queries use layermasks not layer indices
Thanks appreciate it
@slender nymphEven tho it says int
yeah works perfectly if i change code save it and unity reloads everything then play works fine. When i stop the game and play again just stops showing but the debug log keeps working so its somethign to do with no setting the ui active
did you even read the bitmasks link i sent earlier?
So everything works but the UI
bitmasks, including layermasks are just ints. but the layer property on a gameobject expects a layer index not a bitmask
yeah ive just noticed when the game starts now the ui is set to active but on my start method i set it to be inactive
that might be the cause of it
Do me a favor get that bug to happen and check the Ui active state when looking at a interactable and see if its active
@slender nymphI see
Well i mean i need to see if the UI that you want active is actually active and it doesnt have to do with the LeanTween
bool toggles perfectly
ill try remove tween and see if that changes anything
Yeah definitly check that, cause if it is the tween ill have to look at that
yeah works without the tween
something to do with that then
in the start method?
Indeed
instead of disabling the UI directly
do it with the method you already have to do that
on second start up
doesnt even set it inactive
same thing using awake
ok
yeah no totally understand
https://twitter.com/DodgeRollGames/status/593625936131653632/photo/1
How do I make something like this Unity?
can i see the LeanTween code
Didn't look at the link.
Yes
I asked how, not if lol
Ah, I did misread that.
Is that a code question?
Which part?
place sprites in the scene in a way similar to that
I was wondering how to setup up that type of view
Wondering how many degrees the wall and floor are tilted
I assume I would have to use an orthographic camera
Sorry i meant the LeanTween script
oh thats a plugin from asset store
ah
why are you asking this in a code channel
Ok, so not really a code question then. Try asking in #💻┃unity-talk
sprite tilting is so odd but it's actually the most performant way in Unity to prevent clipping
was just using it for some basic animation to learn leantween but i can go without it for now. Youve helped a ton with just getting that working properly and teaching me how to right nice code HAHA
Ill look into it more and see whats going on with this thing
Appreciate it.
could honestly just be ive written the lean tween part incorrect
wait at the end change setOnComplete to setOnStart, just for wonder
same kinda thing on set start. on second start up isnt inactive
https://gdl.space/zusekuqewo.cs Give this a try i may have found a solution
didnt seem to work unfortunately
Damn such a weird circumstance
yeah super weird im gonnna focus on some more basic ui stuff and come back to animations at a later date but appreicaite the help youve been amazing
No problem
Alright, I feel like i have a really dumb question about getting object direction and am missing something obvious
I have gotten my bullet object to spawn on the character, but the bullet only goes left rather than moving based on the players rotation
set the bullet direction to the player's forward direction
or the gun if you're spawning it from that
Well depends on what your using, are you doing it from transform or using force
is that a z coordinate or a mixture of all three?
no
transform
yeah, forward is z facing
Ok i would either do raycast for "Bullet" or using Physics for pullets
like my rigid2d?
yeah if you making a 2D game
cause using tranforms directly can cause a lot of issues with collisions
already fixed the issue of them colliding accidentally
the bullet flew off spinning originally lol
The weapon should have an empty GameObject for the bullet spawn point. The bullet instantiates from that GameObject's transform. It will already point in the "correct" direction the bullet spawn point is facing . . .
oh you're using 2D
Changing the transform directly can cause the bullets to sometimes not even detect collision
transforms are fine, you just need to use fixedtime
and then do the casting yourself
yeah that route is also valid
but if you're new to it all, using the physics from rigidbody is easier
especially for bullets
welp i need to go to the code babies channel lol 🤦♂️
https://www.youtube.com/watch?v=wkKsl1Mfp5M&ab_channel=Brackeys follow through with this video and just see how he sets up his
Let's learn how to shoot enemies!
● Get the The Complete C# Masterclass for only $9,99: https://bit.ly/2xfXE6J
● Instagram: https://instagram.com/brackeysteam/
● Download the Project: https://github.com/Brackeys/2D-Shooting
● Get the 2D Sprites: https://bit.ly/2p6VcvH
♥ Support Brackeys on Patreon: http://patreon.com/brackeys/
·············...
you dont have to copy but it might help you a little bit?
does fixed time relate to delta time or should i research the term?
it's a specific timestep for when unity does physic calculations like collisional checks and raycasts (accumulative forces too)
ill have a look, thx
Ok so you just use playerTransform.right depends on the original direction de player is facing if its left use -player.transform.right
If its up use up...
the issue is the player uses rocket controls
What does that mean
Is it 2d or 3d
2d
The controls dont matter
You want to shoot where the player is facing right?
You change the player rotation in the z coordinate right?
The player originally is looking up?
it should always come out of the front of the character yes
looking right currently
if it spawns from an object that's facing the direction you want, you can simply use that object's direction
Ok then use the players transform
Are u using addforce or velocity
Ur using physics to do it right?
velocity
Ok so do this
Are you instantiating the bullet from the players script
should i sahre the code snippet that handles the bullet so far?
Yah sure
i am
Ok so do it like this
whats the proper foramt? its been a while
thats not the highlighted format, oops
!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.
Just repost please
bulletRb.velocity = transform.right * bulletForce;
@vernal minnow this is all you need
{
//string otherTag = gameObject.tag;
// calculate starting X and Y coordinates
// somewhere at the top edge of the main camera area
float worldHeight = Camera.main.orthographicSize * 2.0F;
float worldWidth = worldHeight * Camera.main.aspect;
Vector2 position;
position.x = Random.value * worldWidth - worldWidth / 2.0F;
//position.y = gameObject.y; // top edge
Debug.Log("Laser 1 Fired Successfully");
// Instantiate object at current player location
GameObject laser = (GameObject)Instantiate(CirclePrefab, transform.position + new Vector3(0.5f, 0.0f, 0), Quaternion.identity);
//Sets the laser on a moving course in a specified direction
Rigidbody2D rb = laser.GetComponent<Rigidbody2D>();
rb.velocity = new Vector2(laserSpeed, 0);
//prevents infinite lasers from being spawned
StartCoroutine(scheduleDestroy(2.0F, laser));
IEnumerator scheduleDestroy(float delay, GameObject target)
{
yield return new WaitForSeconds(delay);
Destroy(target);
}
}```
Also; coroutines should not be nested in other functions, also just use the overload of Destroy that has a time parameter
Well I got to go, hope I helped
Oh yah if you want to destroy the bullet after some time go into the bullet script and at the start funcrion do Destroy(gameobject, seconds)
Seconds is the amount of seconds you want
That's cool. There are tons of other people who can help as well . . .
And, just reference the component you care about instead of GameObject. Referencing your prefab as a Rigidbody2D avoids you having to get the component. (Changing a type will require you re-assign it in the inspector)
Yah I know am sorry for that its just that I needed to go and it was something that I felt like I could help
Next time I'll do it the right way
would that not mess with my other rigidbodys since this is on the player code?
No? Just instead of GameObject CirclePrefab do Rigidbody2D CirclePrefab, so you actually reference the thing you really care about
ah alr
Nope not really instead of GameObject just put Rigidbody2D and use the getcomponent directly
before i try this bulletRb.velocity = transform.right * bulletForce; what is bullet force and bulletRb?
So I'm trying to change my text and it is giving me a NullReferenceException error, how do I assign text in the inspector?
public Text m_MyText;
void Start()
{
// Text sets your text to say this message
m_MyText.text = "Hello world";
}
void Update()
{
if (Input.GetKeyUp(KeyCode.Space))
{
m_MyText.text = "My text has now changed.";
}
}
click the object that has this code
Is this for Legacy maybe?
using UnityEngine.UI;
Still not working.
hmn
send a pic of when you click the object that has the code
i want to see what the inspector looks like
I think it has something to do with public Text m_MyText;
the text has to be assigned right?
That is not a Text, that's a TextMeshProUGUI
alr, im lost the now, vert has ya covered probably
Right, how do I fix that?
Use the correct type?
are you not using legacy?
No, I'm not
try using legacy text
I'm trying to avoid that
No, just use the correct type in the declaration
Could you, please, provide an example of a correct type and declaration?
public TextMeshProUGUI m_MyText;?
Thank you
is there something bad about legacy or is it just outdated?
AFAIK it's better to use TMP but I don't know why
It's fixed resolution

hey guys! What's a good way to check if a mouse button click isn't interacting a UI element?
EventSystem.current.IsPointerOverGameObject()
ayy thanks!
//Set up the new Pointer Event
m_PointerEventData = new PointerEventData(m_EventSystem);
//Set the Pointer Event Position to that of the mouse position
m_PointerEventData.position = Input.mousePosition;
//Create a list of Raycast Results
List<RaycastResult> results = new List<RaycastResult>();
//Raycast using the Graphics Raycaster and mouse click position
m_Raycaster.Raycast(m_PointerEventData, results);
//For every result returned, output the name of the GameObject on the Canvas hit by the Ray
if (results.Count > 0)
{
return true;
}
If you're using the "new" input system because it complains about IsPointerOverGameObject
It doesn't complain to me 🤔
It's been a while but I think the compiler complains if you use it inside one of the key event methods. Something about it being an update behind on the information