#💻┃code-beginner
1 messages · Page 411 of 1
yep, I dunno if its gonna be a lot of load rendering those 3 scenes
maybe its some AAA magic but idk how it runs so efficiently while having stuff like that
When I say "Scene", I actually mean it in a cinematography sense; you don't actually need a whole separate Unity scene to do this. I don't think it would be very taxing performance-wise if the rest of the scene is relatively quiet.
In terms of development speed, you can attach cameras to each of these characters as prefabs and it would expedite the setup process.
You can also consider controlling the UI canvas through code and having a prefab for the tri-split or dual-split cutscene view to efficiently switch between gameplay and different cutscenes. This might help keep it modular.
And as always, it's best to avoid premature optimization. Try an initial approach before considering whether you should take steps to further optimize it. It might be unnecessary
oh my god Quaternion.Euler is being a giant ass to me
i cant get how to use it correctly
its confusing
i just tried making something quick with it, that helped a bit
what is confusing?
im not even sure
i want to figure out how to use it correctly and when i would need it
You would need it when you want to apply a rotation using Euler angles, you know what Euler angles are, right
its x y and z right?
kinda. you know a circle has 360 degrees, those degrees are Euler angles
oh okay
sorry for the late responses
i found out about Quaternion.Euler when i was looking at camera movement scripts
ive been trying to understand why it was used and stuff
so, imagine you have a line going from your head to your feet, that is the Y axis. If I want a rotation that just turns around I can make a Quaternion
Quaternion q = Quaternion.Euler(0,180,0);
transform.rotation = q;
oh okay
yeah that makes more sense, ill try using it and see if i could see how it was used
the values you use in inspector for rotation are euler angles. unity shows euler angles and then converts it to fancy quaternion stuff for the actual rotation. Usually use Quaternion.Euler if i wanted to write in code what a rotation should be (or change by) in terms of euler angles
oh okay
yeah I’m realizing now why it was used in camera movement
thank u for helping me
hello, i am making fps shooter and my camera is jittery
the player is a parent to the camera and when i move the camera (like rotation) it is fine but only when i start moving and rotating the camera the camera movement is very jittery
the rigidbody is interpolate, movement is in fixedUpdate as it is rigidbody movement, and cameramovement is in lateupdate
please help (tell me if you need to see any code)
restart scene button works only once after applying dontdestroyonload()
any ideas why that is?
You should probably provide some information for folks to better help you
I have a button with event system and is interactable but i doesnt work, the button should activate the inventory gameobject
Can someone help me with this bug?
there might be an element blocking the button
check if theres any UI elements overlaying it
you want to delete changes? theres a point where you just re-clone the repo
never seen that error
also i tested it on other levels and it works fine except for level 1
there are none but i managed to fix that bug
stash your current changes in a new branch, then you can revert to a previous commit
if you created a new branch why are you still in main?
Push changes and move to new branch
It has merge conflicts. You should resolve them or discard
Copy the scene file, remove it (in repo), make a commit and push it, place scene back and commit and push again
His scene file contains merge conflicts, you can't commit it like that at all
when making a commit do i commit nothing?
Discard the changes, and go through latest commits and find the last one that works. Copy the scene file from there and commit it to the master. You will probably lose some changes but it is the easiest way
You should commit file removal from repo and paste again the scene file, that usually fixes stuff for me
I don't know how but it does
none work
if every commit has a corrupted scene file there is no way to restore it. Check if you can resolve the merge conflict manually (rarely works for me) or just delete the scene file and recreate it from scratch
Hello guys! I have this script and all I want is for my gameobject to take my sprite that I putted in the Inspect using SpriteRenderer. Im using the same exact script above and its working but now it seems like it doesnt. Did I make a mistake or anything?
private void Create (int level)
{
GameObject myGameObject = new GameObject("Lvl" + level);
SpriteRenderer renderer2 = myGameObject.AddComponent<SpriteRenderer>();
renderer2.sprite = CamilaLvl2;```
On The Sprite Renderer, the Sprite doesnt take the image
I'm using Visual Studio Code and I don't get suggestions when I type something (Here I'm typing time.deltaTime), is there a way to activate it?
!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
hmmm okay checking this out
It is easier to use a prefab with the Sprite component on it and assign the sprite . . .
If it was working before, check that you don't have any errors . . .
like its not assigning anything
Like the Sprite thing is empty
transform.Translate(new Vector2(0.0f, InputManager.GetInstance().GetMove1Value() * ySpeed));
transform.position = new Vector2(transform.position.x, Mathf.Clamp(transform.position.y, -250f, 250f));
trying to clamp my y movement but it wont work. it just snaps to -250 for some reason
are you starting lower than -250? Check what is the actual transform.position.y value before the clamp
im starting at 0
so check what is your position between these two lines? Mathf.Clamp shouldn't just snap you to the minimum value
i have 2 borders that are set at -250 and one at 250 and im at 0 so im right between them
you just said it snaps you to -250, but also you are at 0. Which one is it? Does it snap you in the first frame?
yes
So check with Debug.Log or with debugger what are the actual values in the code
How can I make field serialize like on image in other script.
This doesn't work:
[SerializeField] Action action;
Use UnityEvent instead of Action
thx ☺️
hello, i am making fps shooter and my camera is jittery
the player is a parent to the camera and when i move the camera (like rotation) it is fine but only when i start moving and rotating the camera the camera movement is very jittery
the rigidbody is interpolate, movement is in fixedUpdate as it is rigidbody movement, and cameramovement is in lateupdate
please help (tell me if you need to see any code)
Making smooth camera movement might be tricky. Try to move the camera from under the player and make it follow the player in LateUpdate.
Make sure you're not breaking the interpolation with incorrect rotation or movement.
You should only be moving and rotating your character via the rb methods and properties, like velocity, forces and torque
my camera is in lateupdate
ill check on this soon
how can i log the time on console
to keep track of how long it took to jump
i want to sync it with animation
Record the start and the end time of a jump. check the Time class in the unity api docs
oh ok thanks
yeah i am only moving my cahracter with the rb settings
it might have something to do with the camera object rotating and maybe it is causing the playerobject to shake a bit because it is a capsule collider
public Sprite CamilaLvl2;
private void Create (int level)
{
GameObject myGameObject = new GameObject("Lvl" + level);
SpriteRenderer renderer = myGameObject.AddComponent<SpriteRenderer>();
renderer.sprite = CamilaLvl2;
} ``` Does anyone know why in the runmode, sprite in the SpriteRenderer of the GameObject isnt assigning with the Sprite "CamilaLvl2"?
Can you verify with debugger that CamilaLvl2 is not null?
im not sure
i just swapped the capsule collider with a square collider and it is still happening
it is assigned to a Sprite
Why do you have a camera with a collider as a child of the player? It might be the problem
It is in the editor. You should check in the runtime
nono sorry
i meant the collider of the player
in the runtime, Sprite Field is null
Share a screenshot of your setup in the hierarchy and inspector
in the code, I assigned the Sprite Field with an Image but it doesnt match
Can you show how you do it?
Can you check if the CamilaLvl2 is null in the runtime? Not the sprite in SpriteRenderer
How can I check that?
With debugger. Or just how you check the sprite field in the inspector
this is the hierachy of the player
the camera is in the caamholder
and the player rigidsbody and capsule collider in inspector
while runtime
on canvas
like on the script while running
Try to verify with debugger. If the sprite is not null SpriteRenderer should get it. Unless you have two components and look at the wrong one
Im trying rn to call the function that does this thing in the Start function to see if its a problem with the function itself
But the code gets right everything, like adds all the other script and marks all the things except this thing
And im not quite sure why cause i did this thing earlier in this program and it worked
Try it on the empty scene
It worked
But only
when i assign it in start
not when I need
I cant destroy a gameobject and then add another one?
Are you sure you have only one instance of this class?
what do you mean by that?
Probably not
you might have an instance with correct sprite assigned, but when you call the method you use some other instance without a sprite reference
Testing, it doesnt have anything to do with the destroy function
Like even if its not destroying those 2 its not working
Share the code you use to move the character.
And the camera just in case
I dont think so
Would you want from me to share the code that I call this function?
Or make a mp4 and show it to you?
Hello,
When I create a SO with this script, the object creates correctly but Unity send me this error :
No script asset for Weapon. Check that the definition is in a file of the same name and that it compiles properly.
What I do wrong ?
using UnityEngine;
[CreateAssetMenu(fileName = "New Item", menuName = "Inventory/Item")]
public class Item : ScriptableObject
{
public int id;
public string itemName;
public string description;
public Sprite itemImage;
}
[CreateAssetMenu(fileName = "New Weapon", menuName = "Inventory/Item/Weapon")]
public class Weapon : Item
{
public int damage;
public int reach;
public int cadence;
}
[CreateAssetMenu(fileName = "New Armor", menuName = "Inventory/Item/Armor")]
public class Armor : Item
{
public int armor;
}
Is the code from the second screenshot on the character?
Well, what did I say about rotating the character only via the rb?
Try having all SOs in different .cs files
You can show your code
ok yeah mb, but i want the character to rotate because then players know which way it is facing
You'll need to rotate it via the rb, as I said.
You can use MoveRotation.
is multipy by delta time needed in fixedUpdate function?
public Sprite CamilaLvl2;
private void Create (int level)
{
GameObject myGameObject = new GameObject("Lvl" + level);
SpriteRenderer renderer = myGameObject.AddComponent<SpriteRenderer>();
renderer.sprite = CamilaLvl2;
bc2d = myGameObject.AddComponent<BoxCollider2D>();
rb2d = myGameObject.AddComponent<Rigidbody2D>();
rb2d.gravityScale = 0;
bc2d.isTrigger = true;
}
private void OnTriggerStay2D (Collider2D collision)
{
string thisGameobjectName;
string collisionGameobjectName;
thisGameobjectName = gameObject.name;
collisionGameobjectName = collision.gameObject.name;
if (mouseButtonReleased && thisGameobjectName == "Lvl1" && collisionGameobjectName == "Lvl1")
{
mouseButtonReleased = false;
Destroy(gameObject);
Destroy(collision.gameObject);
Create(2);
}
}```
CamilaLvl2 is assigned
I'm not sure it will help but I'd move Create(2); line to be before Destroy just to be sure
Depends.
unironically i love you
thank you so much
it is working now
depends on what?
ill do it
didnt help
have you tried debugger?
The Frame Debugger?
No, normal debugger in your IDE. With a breakpoint in Create method
If you have a value that represents a change over time, and you're using it to change a value, you must multiply by Time.deltaTime
Velocity times time equals distance.
FixedUpdate runs 50 times per second, rather than a variable number of times per second
idk how to work with it
But the principle is unchanged: you must convert a "per second" value into an absolute value.
Also, in FixedUpdate, Time.deltaTime gives you the same value as Time.fixedDeltaTime, so you can just use the former
how can I find it
You need to have a working IDE first
Visual Studio, VSCode, and Rider all work here
You know your IDE (integerated development environment) is working if it's highlighting errors and suggesting autocompletions
Does Debugger work on the Android Platform?
are you testing in the build? You can make debugger work with android developer builds but it's a little bit harder. Just check in the play mode
and after play what should I press?
You attach your debugger to the Unity process, add a breakpoint and run the scene. Just like it says in the doc
you can do all 3 steps in any order, but you will actually start debugging only when you do all 3
Ok so first one is to put VSC up on the External Tools
if i add a gameobject to a list of gameobjects would the list direct to the original object or create a copy of it?
List<GameObject> drones = new List<GameObject>();
GameObject parent = GameObject.Find("drones");
for (int i = 0; i < parent.transform.childCount; i++)
{
GameObject child = parent.transform.GetChild(i);
drones.Add(child);
}```
to the original. GameObject is a class so reference type
Then press on the right side of the screen on that bug
ok that makes everything a whole lot easier for me ty
there are two big kinds of types:
- value types: you hold the data directly, and you copy it to give it to someone else
- reference types: you hold a pointer to the data, and you copy the pointer to give it to someone else
sorry for still bothering you,but English is not my main language and Im not understanding all of the words from the document.
First one is this thing : Specify the External Script Editor in Unity
Then : Debug in the Unity Editor
If you are using VS Code, there is an instruction on Unity extension page just for that
Im using VSC
so yeah im using it
and im trying to mentain the exact same steps but im still clueless about the other steps
So I should Debug in VSC
do you have VSC set up? Does it highlight syntax and auto-complete? If so, your debugger is probably already set up and you only need to attach it and start the scene
it doenst auto complete things
I have to write everything manually
so that means my debugger isnt setted up
Look for Unity official extension in VS Code and follow instructions there
is this looking good?
no
Ill do this rn
I installed the Unity extension for VSC
Hi. I made a movement system that I want to experiment with in another project, what's the best practice way of making and managing my own library/package in Unity?
Like a Git submodule maybe??
Ayo o/ I need to talk this out because I'm over looking something simple.. I have two colliders meeting (crate & scoreCounter) and both are marked " Is Trigger" One collider is static and has a script to increase a score when a collider marked with the (crate) tag interacts as a trigger.
The void Start works but nothing after does
A tool for sharing your source code with the world!
OnTriggerEnter requires at least one of the objects to have a Rigidbody
so basically @broken cargo,I installed Unity extension
And right now, Im more clueless about the following step
You can just make a Unity package. But if you want to sync it between projects submodule would work
On the left above extensions button
thank you 🙏
FML.. Thanks.. works like a charm
Did you follow all of the instructions in !vscode ?
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
the "VS Code" instructions there walk you through everything you need to do
and after following these I should be able to press the Debug thing thta is above the extensions, and then see something that is related to UNity above
Right? @broken cargo
yes, in the end of the instructions there is a section about debugging
Not in the 2nd doc tho right?
I cant see anything that is related with it
with the Debug
When Ill reach that state, can I still contact you further?
With the debug thing that pops up?
so I can assign a TextMeshProUGUI to a gameobject in the Hierarchy but I can't use the same thing on a prefab in the Project window?
some corrections..
you can't assign a reference to a "gameobject"
you're dragging a reference into a field of a component in the inspector
it is true that the component is attached to a game object, though
Scene objects can only be referenced by other objects in the same scene.
Therefore, assets can't reference scene objects.
hmm Im using cratescorewall gameobject with a big collider wall to detect passing instantiated gameobjects with collider boxes and a tag (crate) to raise a score. The script to detect this is on the cratescorewall gameobject
but the other colliders are a player projectile and moving crates.. all of which are instantiated. So nothing is in the scene until spawned or triggered.
Can you write code within the game and have it execute?
You would need some kind of in-game scripting language
From what I've seen, many games use LUA
Or if you just want simple commands then you can make your own console that you type into and parse strings which execute pre-defined code
Lua is popular because it can be embedded into your game
it's totally separate from your game code
I'm going to need something for my dialogue/sequence system
Already started making my own tokenizer+parser but I kind of died inside
I'll look into that 👍
Note that you can almost certainly avoid writing a parser yourself
Quite a few useful grammars are context-free
I believe C# is context-free
(you've activated an unskippable cutscene; i had to learn this well enough to explain it to undergraduates)
Depending on what you're trying to do, you might even be able to get away with a regular grammar
which you'd parse with...a regular expression! ✨
Heyo, im asking for help regarding character rotation with the new input system.
I´ve made a character controller, and can use WASD without any problems. When i try to run it with the code for rotation however, everything breaks. Im still able to move forward without any problem, but once i move right, left, or backwards the character glitches around. My current code is down below along with a video showcasing the issue. Thanks in advance!
(For context, I want to rotate the player in the direction it is currently moving)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Mover : MonoBehaviour
{
[SerializeField]
private float MoveSpeed = 3f;
[SerializeField]
private int playerIndex = 0;
private CharacterController controller;
private Vector3 moveDirection = Vector3.zero;
private Vector2 inputVector = Vector2.zero;
private void Awake()
{
controller = GetComponent<CharacterController>();
}
public int GetPlayerIndex()
{
return playerIndex;
}
internal Mover FirstOrDefault(Func<object, bool> value)
{
throw new NotImplementedException();
}
public void SetInputVector(Vector2 direction)
{
inputVector = direction;
}
void Update()
{
moveDirection = new Vector3(inputVector.x, 0, inputVector.y);
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= MoveSpeed;
controller.Move(moveDirection * Time.deltaTime);
if(moveDirection != Vector3.zero)
{
transform.forward = moveDirection;
}
}
}
What tool/strategy does one actually use nowadays, from my rather superficial reading I’m hearing all sorts of divergent opinions ranging from handmade, bison, antler to using the equivalent generators that exist as libraries for C/++? Do you have any more insight?
I haven't had to do this in C# specifically, which is why I thought of antlr first
why does this not work?
int Number = 6
string StringNumber = (string) Number? he says i cant convert it? but i can convert a double to int?
yes, beacuse there is no explicit conversion from int to string
Number.ToString()
why do u need to do that and not with double to int?
because there is an explicit conversion defined for double to become an int
because a string is not a numeric type
hmmm okay, got it
My issue with a DSL as a solution to say a dialogue system is the crappiness of maintaining a language, solo, as its requirements change and procedural features get added.
Yeah, it's not what I'd reach for first.
But it would be so nice to be able to maintain a nice dsl… question is just: how?
A tangent: I made a binary format to export vertex attributes from Blender to Unity
I wound up using Kaitai Struct to define the binary format and debug it
I didn't use it to generate a parser, though.
But it was very useful to codify the format in one place and to be able to check that the files I was producing were valid
Interesting
Maybe solving the maintenance problem must be part of the design
it’s probably more doable for data exchange formats and markup than for stuff that describes procedures
yeah, it's easy when all of your files are being machine-generated
making changes to the format doesn't require any manual labor beyond re-exporting
indeed, and that’s the only situation where I’ve ever made custom formats.
making something for humans is no fun 🤩
they get annoyed when you change stuff 🤦♂️
as I continue to make major changes to how systems work, I can only imagine how much worse the process would be if other people depended on my game code
Guys, I need help. I'm learning to use the 2D Tilemap, and I get this bug. The IsGrounded funtion returns True when my character is on the ground, as expected. But the Y velocity when my character moves to the right stays higher than 0, which make Unity think my character is Jumping, while the IsGrounded is still true. The animation then flicks between running and jump animation. This only happens when my character run on the tilemap, not on other game objects.
This is the code if you want to know https://gdl.space/zaximetini.cs
anyone know what the issue is with my code on my bullet prefab? just trying to draw a super simple raycast and then visualize it, but nothing is happening.
void FixedUpdate()
{
RaycastHit2D ray = Physics2D.Raycast(transform.position, transform.up, MaxDistance, LayerMask.GetMask("Scene"));
Debug.DrawRay(transform.position, transform.up * MaxDistance, Color.green);
if(ray.collider != null){
print("Object Hit at " + ray.collider.name+ "!");
} else {
print("Collider hit nothing :C)");
}
}
so nothing is being logged at all?
it keeps saying nothing is being hit, and no raycast debug is being drawn
perhaps MaxDistance is zero
nope, set it to 100
is it actually set to 100 on your prefab, though?
a field initializer that sets the field to 100 won't matter if the prefab has that field set to 0
If MaxDistance is a serialized field, then that doesn't mean it's 100 on your prefab. Go look at it in the inspector.
Is transform.up pointing into the screen, perhaps?
that would mean your object is rotated by 90 degree on the X or Y axes
i'm not sure, should i try changing it to transform.forward?
Select an instance of the bullet prefab in play mode and look at the handles.
Make sure you're set to pivot + local
The blue arrow should be pointing into the screen. The red and green arrows should be parallel to the screen.
oh, i just had the gizmo off i think. looks like i'm slow
press W to get the move handles
yep, i'm seeing them
being a unity noob has it's drawbacks. now i need to make the bullets follow the raycast
Show me a screenshot of the bullet.
the bullet in the inspector? in game?
Yes.
both the inspector and the scene view
the entire editor window, really
you've collapsed the Transform part, which is very important
my mistake, one moment
and I'm looking for an actual instance of the bullet while the game is playing
since you could be changing its rotation when you instantiate it
sure
shoot a bullet, pause the game, select the bullet, and then screenshot the entire window
the entire editor window
mkay
with the bullet selected, with the "move" tool selected (press W)
Okay, the handles are pointing in reasonable directions
You have gizmos off, so you're not going to see the DrawRay lines
they're back on now, my mistake
Do the lines appear now?
ah, I thought you were talking about the handles here
now i need to code the bullets to follow the raycast, as well as destroy and trigger on any collision
I didn't realize you'd started seeing the DrawRay lines there
yep, i just didn't realize i needed to turn them on. thanks for the help, friend! i'll probably need more sooner rather then later
bullet.velocity = ray.direction * speed
sir yes sir, implementing it now
it doesn't like ray.directionRayCastHit2D does not contain a definition for it
that's a Ray, not RaycastHit2D
but yes, your ray is a RaycastHit2D
(you should name it hit)
Your code doesn't create a Ray, so just use transform.up
ah, i see, thank you
check your using directives
pretty simple namespace collision
yeah but im not sure why it suddenly appeared
it was working before
then now it gives me an error
because you added the appropriate using directives to create it
yeah i removed the one i didnt need
thanks
thank you for your help, friends. now begins the difficult part. from where the raycast collides with the scene, i'm going to need it to create a new raycast for the bullet to follow afterwards- this is because a core mechanic of my game is bouncing bullets off walls. i figure i'll need some mathf trigonometry sort of code, any suggestions?
nah
Vector2.Reflect
you give it an incoming vector and a normal vector (you get the latter from the RaycastHit2D)
you should have a look at the static methods of Vector2/Vector3 and Quaternion
on it!
Why dosent the character stand up 750 for the hips and 200 for the rest?
It does what its suppose to do but not standing up
No ig i just forgot to lock rotation on the hips?
i have no idea what your ragdoll looks like or what you're doing
so it's kind of hard to tell you anything
I have made an active ragdoll
why does this not work? i'm a bit confused on how i can calculate the reflection when i can't get the direction of the bullet (rhymes!)
Vector2 reflectionDirection = Vector2.Reflect(hit.direction, hit.normal);
navarone thought your ray variable was a Ray
yeah, i changed it to 'hit' to be more clear
RaycastHit2D does not have a direction field becaus that would be redundant
yeah, i suppose that makes sense
i'm just confused as to what i would put in the first part of Vector2.Reflect
the direction the bullet is going
again, you already know what it is
you used it for the raycast, didn't you?
i used transform.position, and transform.up
maybe make a variable for it ?
you're basically typing it 3 times now
right, i'm trying to. just not sure how exactly to update said variable with the direction of the bullet
i can't use transform.rotation or something
wdym just use the drection of your raycast but Im saying make it a variable
raycast, drawray and now bullet have typed 3 transform.up you are accessing up property 3 times
I don't understand what the problem is
oh, i was misunderstanding something
transform.up is a Vector3; it'll get implicitly converted to a Vector2 when you pass it into Vector2.Reflect
i get it now. my mistake
exactly, i didn't realize this
this what I was suggesting btw
Vector3 direction = transform.up;
RaycastHit2D rayHit = Physics2D.Raycast(transform.position, direction, MaxDistance, LayerMask.GetMask("Scene"));
Debug.DrawRay(transform.position, direction * MaxDistance, Color.green);
Rigidbody2D bullet = Instantiate(prefab, firepoint.position, Quaternion.identity);
bullet.velocity = direction * speed;```
i see, that's definitely cleaner then mine
all I'm doing is storing the direction so you don't have to access the same thing 2-3 times. What's more important though is you only have to "track it" in one point, obviously its no big deal with transform.up but its good habit to not repeat code, try to cache(store) stuff
yep, i've implemented that into my code as well. right now i'm trying to figure out how to do the bounce
something like this on collision?
Vector2 reflectionDirection = Vector2.Reflect(direction, hit.normal);
direction = reflectionDirection;
transform.Translate(direction * Time.deltaTime * BulletSpeed);
if this is on the bullet ? how are you detecting a hit ?
just a simple private void OnCollisionEnter2D(Collision2D collision)
is the bullet rigidbody ? don't use translation
it is rigidbody, good point
stick with velocity
will do
also I would normalize the incoming direction then multiply it again by bullet speed so you have consistent reflect speed
okay, i'll try that. you think this should happen in the if statement earlier in the code, or on collision? probably on collision i figure
private void OnCollisionEnter2D(Collision2D collision)
{
life--;
if(life < 0)
{
Destroy(gameObject);
return;
}
print("Collision!");
}
not printing collision, i wonder why
why do you have a ; for Life--?
valid
you dont need that
i defintiley do, no?
yes
i have never used a ; for adding or subtracting a float
Then you've never worked in c#
show how ur moving the bullet
sir yes sir
void FixedUpdate()
{
Vector3 direction = transform.up;
RaycastHit2D hit = Physics2D.Raycast(transform.position, direction, MaxDistance, LayerMask.GetMask("Scene"));
Debug.DrawRay(transform.position, direction * MaxDistance, Color.green);
Bullet.velocity = (direction * BulletSpeed);
if(hit.collider != null){
print("Object Hit at " + hit.collider.name+ "!");
} else {
print("Collider hit nothing :C)");
}
}
it's my first time working with raycasts, so i'm still figuring it out
looks fine here and the OnCollision is a bullet script ?
yep
where are you grabbing Bullet and why is it a field
before void Start, "public Rigidbody2D Bullet;"
huh ? do you only have 1 bullet or something?
how do you mean? this is the prefab for the bullet
are you not instantiating them ?
im so confused then why is Bullet prefab here
not the movement for the bullet. You said instantiation is in a diff script
it is.
void Update()
{
if (Input.GetKeyDown(KeyCode.R) == true) {
Fire();
}
}
public void Fire()
{
GameObject bullet = Instantiate(BulletPrefab, transform.position, transform.rotation);
}
that's in the spawner object
so how do you pass this local bullet to that other script to assign direction ?
i don't? all that the spawner script does is check for keypress and spawn the bullet at it's location and rotation, the script inside of the bullet is what creates the raycast and moves to it (which works atm)
when the prefab spawns a clone in, the script is attatched to the clone, and it moves itself
it's working perfectly fine atm
which script moves it
dude. there is a script on the prefab titled "BulletScript" which moves the bullet
I know you're confusing me cause you got 3-4 diff scripts doing different things lol
not really dawg! i've got one to spawn in the bullet on keypress, everything else happens in the script attached to the bullet
here's the whole thing, since you asked
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEditor;
using UnityEditor.Experimental.GraphView;
using UnityEditor.SearchService;
using UnityEngine;
public class BulletMover : MonoBehaviour
{
public Rigidbody2D Bullet;
public float BulletSpeed;
public Collider2D BulletCollider;
public float MaxDistance = 100f;
public int life = 3;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void FixedUpdate()
{
Vector3 direction = transform.up;
RaycastHit2D hit = Physics2D.Raycast(transform.position, direction, MaxDistance, LayerMask.GetMask("Scene"));
Debug.DrawRay(transform.position, direction * MaxDistance, Color.green);
Bullet.velocity = (direction * BulletSpeed);
if(hit.collider != null){
print("Object Hit at " + hit.collider.name+ "!");
} else {
print("Collider hit nothing :C)");
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
life--;
if(life < 0)
{
Destroy(gameObject);
return;
}
print("Collision!");
}
}
ok I see so the raycast is not on a weapon but the bullet itself..
yep, that's what i was trying to say lol
I didn't understand the purpose sorry so I thought it was a weapon
Unity is great game engine isn't it ?
no worries dude! i appreciate it
so the bullet does move? and what happens when it hits wall does it stop
yes.. when it works
nope, passes right through lmao
does the raycast hit?
how fast is the bullet going ?
10 atm
make sure Continuous detection is enabled for collision mode
nope, passes right through
and do walls have colliders
which is odd considering that i specifically tell it to collide with the scene
let me try that rq
a scene is a container of gameobjects
you mean the walls / environment
nono, i mean the tag named "scene"
which is attatched to the walls
not the best name now that i think of it lmao
Layermasks are not tags
no beans
nono i mean layer
jesus i need to use the right words lmao
show both inspectors
bullet and a wall
did you try making raycast longer?
if the bullet is not colliding at all raycast isn't the issue
the raycast should stop when it hits a wall though, no? it goes right through
nothing stops the raycast drawray
if thats what u mean
alright, noted
the only thing you would see is Console logs printing
print("Object Hit at " + hit.collider.name+ "!");
true
print my man?
are those printing, also try showing both inspectors (walls and bullet)
hold on, i have an idea to fix it. i think i set some of this up wrong
printist
hm, not sure. i have the obstacles set to the layer 'obstacle', and the bullet, 'bullet', and so forth and so on. but despite naming obstacle in the raycast parameters, it doesn't collide
you're not showing what I asked 🤷♂️ we're on the same problem
also your Layer is Obstacle but your script is looking for "Scene"
no, i changed it
RaycastHit2D hit = Physics2D.Raycast(transform.position, direction, MaxDistance, LayerMask.GetMask("Obstacle"));
yet it still doesn't collide
the physical bullet should be colliding regardless of raycast
show the rigidbody2D settings on the tilemap
also your collider isn't set to Used by Composite
nothing to show, it's set to static
could we see the bullet collider?
double lifting as well
didn't you guys tell me to set it to trigger? lmao
I never did
spam.. too short of a reply to be meaningful
that fixed it, nice
alr
btw you dont reeally need that raycast
that has 0 to do with collisions
its only used for detections of colliders (it doesn't physically stop any objects)
i see, gonna take a short walk, will be back later to continue failing
hell ya
failure is how you build skills up
only if u learn from them 😉
fact
tru
is unity6 lts yet? 😅
i wake up wondering every morning
literally cant wait.. im having anxiety
what feature are you waiting for most to use in lts
ya, i like the UI more tbh
and i figure it wont get reverted.. soo i just want to get my bulk working in there
yeah its nicer than before with the bigger tabs/buttons
mmhmm it def feels cleaner than i used to be
wish they could improve the compiling speeds though and switch to Core already
i keep hearing that.. but i haven't noticed it being any slower than my 2022 projects
I think the speeds would improve greatly if we are on newer .net
it's not any slower, but it'd be nice for it to be faster :p
i strongly concur
so are they gonna have to call it CoreBehaviour after the switch 🤔
if my project gets bad enough i just disable everything and manually compile
or restart the PC that always speeds it up 50% minimum
CoreBehaviour has a nice ring to it
is there any way to add a vector to a vector?
yes?
have you tried it?
just add them?
lol
perhaps you tried to add a Vector2 and a Vector3
you cant multiply them but you can add/subtract
unity doesnt like the way i do it
show how u do it
ah
probably what fen said
explain what you tried to do and what the error is
oh
ya, thats different
yes
in 2d i always work with 3D vectors just cause of that annoyance with having to cast it or you get error
u can plug in majority of the 2d stuff into a 3d vector.. soo why not
public Sprite CamilaLvl2;
private void Create (int level)
{
GameObject myGameObject = new GameObject("Lvl" + level);
SpriteRenderer renderer = myGameObject.AddComponent<SpriteRenderer>();
renderer.sprite = CamilaLvl2;
} ``` Does anyone know why in the runmode, sprite in the SpriteRenderer of the GameObject isnt assigning with the Sprite "CamilaLvl2"?
where the script is, its assigned a image to it
But in runtime, the image is not assigning
I really need help
so that screenshot is the Sprite Renderer that you add during runtime?
log everything relevant at the end of Create
to make sure that your CamilaLvl2 field isn't mysterious getting set to null
where is this script exactly?
find out whats going wrong
Ill show you exactly the entire script, and when I call it
private void Create (int level)
{
GameObject myGameObject = new GameObject("Lvl" + level);
SpriteRenderer renderer = myGameObject.AddComponent<SpriteRenderer>();
renderer.sprite = CamilaLvl2;
bc2d = myGameObject.AddComponent<BoxCollider2D>();
rb2d = myGameObject.AddComponent<Rigidbody2D>();
rb2d.gravityScale = 0;
bc2d.isTrigger = true;
}
{
string thisGameobjectName;
string collisionGameobjectName;
thisGameobjectName = gameObject.name;
collisionGameobjectName = collision.gameObject.name;
if (mouseButtonReleased && thisGameobjectName == "Lvl1" && collisionGameobjectName == "Lvl1")
{
mouseButtonReleased = false;
Create(2);
Destroy(gameObject);
Destroy(collision.gameObject);
}
}```
and when I call it
I meant which object has it
the inspector, you only showed a cropped version of the field CamilaLvl2
Canvas
script is on a canvas and has OnTriggerStay2D in the script?
UI elements don't use Triggers
UI objects should probably not have any physics components..
Ok so basically
The Canvas has the script
in the canvas it exists 2 game objects
that use the ontriggerstay2d
but why
public class ButtonClicker : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IPointerEnterHandler, IPointerExitHandler
{
bool isHovering;
public void OnPointerEnter(PointerEventData eventData)
{
isHovering = true;
Debug.Log($"Hovering over: {gameObject.name}");
}
public void OnPointerExit(PointerEventData eventData)
{
isHovering = false;
}
public void OnPointerDown(PointerEventData eventData)
{
if (isHovering) // redundant
{
Debug.Log($"Clicked on: {gameObject.name}");
}
}
public void OnPointerUp(PointerEventData eventData)
{
}
}
``` for UI you need a system like this
I think they are trying to detect collisions between ui elements
no
im trying to detect collision between two gameobjects
that also has the script in them
because I store all of the gameobject in canvas?
why?
at this point it would help us to see the entire hierarchy with inspectors...
this is tehe hierarchy
so those Lvl1 are the objects
i know they are objects, those are all gameobjects
what is the purpose of those objects
wait wait wait a bit
it was a simple question
#💻┃code-beginner message
on the inspector field
on the gameobjects part of script
all of them are empty as they used to
this is the inspector of the gameobject
array[] has left the chat
how can I assign the "Camilalvl2" to a image of a script inside of the script
ever heard of an array
tbh, no
did you debug all ur values like Fen mentioned?
with =
i wasnt able to make that thing
you mean you weren't able to debug the values?
what?
i wasnt able to open the debuger
to assign anything you need =
to setup the debugger
You can use Debug.Log instead
you just need to console window.. and Debug.Log();
just put the variables inside the ()s
uOffset = (adjPos.x % tilingFactor) * tileSize;
vOffset = (adjPos.y % tilingFactor) * tileSize;
break;
case Direction.East: //X+
uOffset = (adjPos.z % tilingFactor) * tileSize;
vOffset = (adjPos.y % tilingFactor) * tileSize;
break;
case Direction.West: //X-
uOffset = (adjPos.z % tilingFactor) * tileSize;
vOffset = (adjPos.y % tilingFactor) * tileSize;
break;
}
uvs.Add(new Vector2(uOffset, vOffset + tileSize));
uvs.Add(new Vector2(uOffset + tileSize, vOffset + tileSize));
uvs.Add(new Vector2(uOffset + tileSize, vOffset));
uvs.Add(new Vector2(uOffset, vOffset));``` left some cases out to make the message shorter, how can i correct the offsets for z- x+ and y-? this work for the other 3 directions
tbh this probably belongs in #archived-code-general
@full kite I recommend some basic courses at this point though. An array is a basic you absolutely should know at this point
https://www.w3schools.com/cs/index.php
And then
https://learn.unity.com/pathways
It will help a LOT
How do I start a walking sound fx when walking? I'm having tries which do work in a way... But not perfect. What is the solution?
do you have animation ? like walking
different solutions available
Animation events, timers, distance checks, etc
you can do it w/ animation events..
Yes I'm doing this with anim events
yes animation event
or u can do it with a timer / distance traveled
so navarone, here, how can I update it to work properly
yea navarone.. how he do it 👀
it looks correct but you need that field to not be null lol
firstly I need to assign to the new created gameobjcet the script, which I did, but how do I assign the image to the script
Then make the event trigger a method that plays the sound 🤷♂️
and how can I switch it
cant
why not?
cause that gameobject is being created inside of the game
renderer.sprite = CamilaLvl2;
Debug.Log(renderer.sprite != null ? "Sprite assigned successfully." : "Failed to assign sprite.");```
Im talking about the First one
Then pass the reference returned from Instantiate
still same
the one you use to pass to the instantiated one
where tf is the condition?
how can I do it
if what?
Not that simple. It isnt smooth and the sound gets either silent by the next event or it restart before it ends
assign it
PlayOneShot
this gameobject that has the inspector null, is being created during the script
i cant assign it to the inspector cause I donlt have the inspector when Im not in run time
Why is it any different than Play
you said this is the one that runs Create
It will not cut off when you call the next play. They overlap
As for silence, that is normal. Add some ambience and you won't notice
Let me clarify it
I mean overlapping isnt really what I need either
When I'm walking its not normal to have silence tho
I assign to the gameobject the script
You said it restarts before it ends. PlayOneShot makes that not happen
your system is overcomplicated because its poorly written
redo it, so you understand it
It is. If you take a step and stop, the FOOTSTEP sound would be silent.
There should be OTHER sounds that cover it
i dont need to redo it
my main question rn is how to
put to that field an image
inside of the script
I meant that if I'm just walking the sound effect suddenly stops for like 4 seconds. It is because I chose to change direction with wasd I reckon
if you don't understand how to pass references , you're doing more than you have knowledge of then i would suggest learning how those work
Yeah, so.... PlayOneShot will fix that
Because the sound will not cut off. It will always play until completion
Sure thank you. I'm going to try it.
What if I want it to cut off? Let's say, the player went from concrete to sand, and I want to cutoff concrete footsteps ?
Usually you should check the material before playing the sound. The footstep (in real life) would not cut off, just the next one would start as the other material, and the previous would still ring out. That is how I do with sound design in film and games. Because a footstep is mostly an impact (immediate) and some friction. That would still happen
There is a stop method though
I have the function setup, I was just curious about the method you use these
A stop method would stop the two fxs tho
Correct. I would simply not stop it
Or have multiple sources as a workaround if I REALLY need it (I haven't for this situation)
Thats not really helpful nor useful to have multiple sources in my opinion. Thanks mate
I'm.... sorry?
to have multiple sources for footsteps.. ya i agree..
but multiple sources in general makes alot of sense.. and is common
In my custom case*
That is exactly what I was saying.
yup, i was clarifying for him
Yeah, was just letting you know you were spot on. Thanks
I understood what you were saying mate 😆
Althought I was never into sound design...
sound design is my least favorite thing about game-dev
i fumble my way thru audacity.. make a clip and then OneShot() that thang
Mainly because the lack of knowledge right? Same for me, but I yet to have the courage and the effort to actually ponder around with it
hard to judge tone/context w/ messages sometimes sorry
nah ive figured out my system pretty well after a bit of playing..
I'm definitely bad at making it clear haha
i have an audiomanager that has references to all types of sources that play different things
(menu sounds, boom sounds, player sounds, etc) then they all have OneShot() methods.. and i just pass in the clip from the script im calling upon the AudioManager from
I just have like... Random sources
until u name/ categorize/ and assign them somewhere
and then they're structured and not-random 🙂
foreach (char c in line.ToCharArray())
{
bool specialCharacter;
if (c == '?' || c == '.' || c == ',' || c == ':' ||
c == ';' || c == '!' || c == '-')
{
specialCharacter = true;
yield return new WaitForSeconds(interpunctuationDelay);
}
else
{
specialCharacter = false;
}
if (c == '<' || addingRichText)
{
addingRichText = true;
if (c == '>')
{
addingRichText = false;
}
}
if (!specialCharacter || !addingRichText)
{
PlayDialogueSound(text.maxVisibleCharacters, text.text[text.maxVisibleCharacters]);
text.maxVisibleCharacters++;
yield return new WaitForSeconds(1f / charactersPerSecond);
}
}
trying to make it so that my dialogue doesnt play a sound when a special character comes but its not working.
public AudioClip intro;
public void PlayTempUISFX() => atmosphericSource.PlayOneShot(intro);
public AudioClip gunshot;
public void PlayGunShot() => playerSource.PlayOneShot(gunshot);
public AudioClip[] hurt;
public void PlayHurtSound() => playerSource.PlayOneShot(hurt[Random.Range(0, hurt.Length)]);
public AudioClip basehit;
public void PlayHit() => interactionSource.PlayOneShot(basehit);```
thankyou for fixing that random if 🙂
👍
my guess would be that its not registering when charactes are special
oh wait
thefor all of em are !special
no it does because the delay works
okay
Debug.Log($"Special character is: {specialCharacter}");
debug it everywhere thruout those functions
it does debug
so its true?
yeah
i have an else statement at the bottom
if (!specialCharacter || !addingRichText) <-- means if its not true
oooor if not adding richtext
time.deltatime basically as a numerical value that increases with time right?
if either one of those are conditions return true ur dialog sound will play
its time between the last frame and the new one
delta Δ
precisely
oh k
correct
why for moving player everyone multiplies move speed with time.delta time
remove one of em.. and test w/ just the !specialCharacter
so it can be framerate independent
okay
b/c if u dont a computer running faster frames per second is gonna run faster than a player with a slower machine
multiplying it w/ delta time makes it frame independant
sooo both machines will move same distance.. no matter the frame rate
exactly
when i remove the || !addingRichText for some reason the dialogue registers the last normal character as a special character and the special character doesnt even show up
strange..
i'd have to test it a bit on my machine to figure it out.. i dont see anything that stands out to me a being wrong from the code u sent
i tried and i able able to directly use transofrm.position in visual studio
why cant i do this for other compnents like rigidbody and animator
!ide is it configured correctly?
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
for that i need to getcompnent or make an instance i think
should i send you my unityproj?
no.. i'll just rob ur script
then how would you test it
debugs
Hello
ok
hello Nugget
How do i make a collider move left/right with left and right direction keys
you dont need to say hello; just ask your question immediately
but hello to you too
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
input.getaxisraw("horizontal"
why not make it smooth though
i just odnt like the smoothing uunlesss im doing it on purpose
oh ic
ok then
b/c its more consisitent w/ a 0 or 1 value
yeah thats true
i can multiply it by my speed variable.. and as soon as i release the keys i know my speed is going to be 0
instead of 1, .9, .5 , .432, .2 0
actually can u share the entire script for 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.
sure but its pretty long
sure
thanks imma look it over i cant promise anything tho
nw
ohhh its how u update ur string
the issue is that text.maxVisibleCharacters is being incremented for every character, but PlayDialogueSound is still called for all characters, including special characters and rich text tags.
private IEnumerator DisplayLine(string line)
{
text.text = line;
text.maxVisibleCharacters = 0;
continueButton.SetActive(false);
HideChoices();
canContinueLine = false;
bool addingRichText = false;
int visibleCharacterIndex = 0; // Counter for visible characters
foreach (char c in line.ToCharArray())
{
bool specialCharacter = (c == '?' || c == '.' || c == ',' || c == ':' || c == ';' || c == '!' || c == '-');
if (specialCharacter)
{
yield return new WaitForSeconds(interpunctuationDelay);
}
if (InputManager.GetInstance().GetContinuePressed() && canSkip)
{
text.maxVisibleCharacters = line.Length;
break;
}
if (c == '<' || addingRichText)
{
addingRichText = true;
if (c == '>')
{
addingRichText = false;
}
}
else
{
if (!specialCharacter)
{
PlayDialogueSound(visibleCharacterIndex, c);
visibleCharacterIndex++;
}
text.maxVisibleCharacters++;
yield return new WaitForSeconds(1f / charactersPerSecond);
}
}
continueButton.SetActive(true);
DisplayChoices();
canContinueLine = true;
}``` try this
hey shouldnt then i just always use Time.deltatime?
for movement
theres times u shouldnt
dont ever multiply ur inputs w/ it before the movement code
dont use it in FixedUpdate
use fixedDeltaTime instead
oh ok
Time.deltaTime returns the value of Time.fixedDeltaTime when used from FixedUpdate
i keep forgetting that.. i guess its fine in that case then
those 🧠 smart unity devs
also any time ur incrementing something
myValue += newValue <-- this would increment differently for different framerates..
soo use myValue += newValue * deltaTime;
same with *= or any other incrementing type of method
Can an On Trigger collider trigger another On Trigger collider?
okiee
Ayo, which of the following 2 decalrations is better for a parameter thats only gonna be used inside its class, and the class aint gonna be called from any other script.
[SerializeField] private GameObject obj;
public GameObject obj;`
the first. if other objects don't need access to it then it does not need to be public
it's also not a parameter, but a field
Got it, thanks 🤙
I want to make levels,
30 scenes for 30 levels ? ( just a small 100*100 terrain level)
or 30 levels in 1 scene itself ( and how to do it)
it really depends on game complexity. It can be 30 scenes, 30 prefabs, or even 30 files that contain the level data and one LevelBuilder
Ok i was just scared that putting 30 scenes is overkill for mobile platform , as it may increase build size and not the way people do it .
for eg a simple shooting game with 30 small levels .
@rocky canyon i dont mean to be irritatating but; have you found anything? ive asked but found nothing still
If you reuse assets between scenes it won't impact build size that much. Scene is just a list of IDs
oh thanks , i will just pack reusable assets/ character/enemies into a prefab . hope thats enough
i am not able to rotate the sprite properly
changing z rotation should rotate it abot pivot right
like in the scene editor when i increase the z value it rotates perfectly about pivot
show how you rotate in code
but when i do the same using code , the z value increses correctly but it doesnt rotate that way
like this
so is it rotating at all ?
it is but its rotating like pendulum
not like a wheel about pivot at centre
which is very weird
Because Translate moves in local space
When you rotate it, it changes where Translate will move you
You can use world space in Translate with an extra parameter. Or move by setting position directly
i want this saw to go back and forth and spin at the same time
Really the visual part of the saw should be a child object
indeed
And you animate the child however you want
Using multiple objects dramatically simplifies things
oh ok
- Sawblade <-- circle collider
- Sprite <-- sprite renderer
A Rigidbody can use any collider that's parented to it
the child or parent?
You generally want it up top
oh thanks a lot
It matters less if it's a kinematic rigidbody, since it won't be moving around on its own
But I'd still put it on the parent.
i dont understand why this requires a "workaround" instead of just making the local scale x/y equal the calculation?
could someone explain why that is to me?
transform.localScale is actually a property
when you access it, you're calling a method that gives you a Vector3
Vector3 is a value type. This means that you aren't holding a reference to the actual object somewhere else -- you hold the value itself
what about localScale.x though? normally you can just access an x value of a vector3 and change it normally
excuse me where is textures chat?
should i avoid using void Start() and void Update() in logic scripts?
Modifying a field on the Vector3 would be totally pointless: you'd be modifying the copy you got back from transform.localScale
so it's a compile error
Fen you helped me earlier where is the texture chat?
Or help my bad.
as in, a script that doesn't derive from MonoBeahviour or any other unity class?
but how does that differ from what i did in the screenshot
you store the copy in a local variable
you modify that copy
and then you store the copy back into transform.localScale
just a script that handles stuff like loading scenes, game over ui and loading or saving data
Okay, but does your script inherit from MonoBehaviour?
excuse me where is texture chat? or help my textures bugging
there is not a "textures" chat. you can ask in #💻┃unity-talk if you're unsure where to ask about something.
this is definitely not a code problem
thats why i asked for the texture help bro
yh its a component script from a invisible gameobject, so it does
remember: transform.localScale is not a field. It's not just a variable. It's actually calling a method that returns something
in that case, use Start and Update if you need to run code when the component is created or every frame
there's nothing really special here
ight thanks
What would be the best way to create a enemy that is able to hit the player? I don't mean the player not being able to touch the enemy at all, I mean the enemy hits and only does damage when the hit connects with the player
I feel like most tutorials on YT only go over the player not being able to touch the enemy at all
Would you make a collider appear and disappear in time with the animation? Or use a raycast?
spherecast, or something
overlap
raycast good too, is just too thin for melee
ah ty
I have the weirdest problem and I cant figure out a solution for like 2 hours straight.
Basically my UI is alright when im starting in 1920x1080. When I change it to 720x1560 nothing changes.
But when my UI is starting in 720x1560 it goes in all directions some gameobjects, and when im changing to 1920x1080 all are dessapearing. When im putting it on my phone (720x1560 resolution) I see them as I start my run time in 720x1560 on my PC. All of them have an anchor and i really dont know why it happens. Can somebody help me?
@rich adder
This code is in void Update() and after it reaches for example 10 i want it to increment the value only once because now when the enemy hits score 10 it adds 1 every frame because he hasnt reached the score 11 yet, how do i make it to wait
if (gameManager.playerScore >= 10 && gameManager.playerScore % 10 == 0)
{
moveSpeed += 1;
}
You could consider adding a collider with IsTrigger set to True and animating an attack for the mesh that the collider is attached to, and if the attacking mesh overlaps with the player, deal damage to the player
Cant Raycasts be inn eachoter?
Can you describe this problem a little more clearly? The code you posted, if it's in update, makes the player extremely fast once their score reaches 10 or is at 20, 30, 40, 50, etc., or another number >=10 and evenly divisible by 10.
@river quiver
Note: Update triggers every frame-per-second update, which means faster computers will receive faster iterations of logic which is probably not what you want
I only Get one of the Debug logs?
Putting it in Update makes little sense. Run this code only when whatever happens that should add score happens
Then the other Raycast isn't hitting anything
it did until i made the other one longer
I have the weirdest problem and I cant figure out a solution for like 2 hours straight.
Basically my UI is alright when im starting in 1920x1080. When I change it to 720x1560 nothing changes.
But when my UI is starting in 720x1560 it goes in all directions some gameobjects, and when im changing to 1920x1080 all are dessapearing. When im putting it on my phone (720x1560 resolution) I see them as I start my run time in 720x1560 on my PC. All of them have an anchor and i really dont know why it happens. Can somebody help me?
Have you tried tweaking the Canvas Scaler component on your Canvas?
I don't know what "in each other" means. Raycasts are instantaneous. They can't interact with each other.
it goes in all directions some gameobjects
Do you mean that your game starts with some parts of your UI in the wrong positions?
indeed
like missplaced
but only few of them
they probably have bad anchors, then
or your UI has LayoutGroups and you've got some incorrectly configured objects
are you using HorizontalLayoutGroup/VerticalLayoutGroup?
I have a feeling something is wrapping or getting stretched due to the different resolution.
Can you post a picture of before/after to help identify the issue?
like with this line
myGameObject.transform.position = new Vector3(newX, newY, 0);
ok one second
this sets an exact position on the screen, assuming this is a "Screen Space - Overlay" canvas
why are you doing this?
vOffset = (adjPos.y % tilingFactor) * tileSize;
uvs.Add(new Vector2(uOffset, vOffset + tileSize));
uvs.Add(new Vector2(uOffset + tileSize, vOffset + tileSize));
uvs.Add(new Vector2(uOffset + tileSize, vOffset));
uvs.Add(new Vector2(uOffset, vOffset));``` it looks like im getting the output im expecting for the u and v values. but i can't figure out how to apply the correct offsets for the different directions
screen space - camera
it is
first one is 720x1560
and the second one is 1920x1080
Can you clarify what you mean by "apply the correct offsets for the different directions"?
hey fen, remember all that work we did to make the bullet work right and follow the raycast? well it randomly doesn't work now :l could i send you the code?
How can i make the "item" go up also? Item.GetComponent<Rigidbody>().AddForce(ItemHand.transform.forward * 100);
transform.up?
Do you have the code that sets the positions of these two sprites? Can we see them side by side?
Are these things both UI Elements?
I know, but do i just multiply it with Transform.forward?
What ratking said - Add a force using transform.up * (forcevalue)
the carpet is an UI element
the cammel is a gameobject
yeah, transform.up * speed
transform.up and transform.forward are two different directions
It would probably be better to use transform.TransformDirection and plug in a custom local space vector
the carpet is setten up with coords in the inspector
and the second one is with that code
Okay
This is probably your issue
They are being set through two different mechanisms, and one of them is dependent on the resolution.
like with this line
myGameObject.transform.position = new Vector3(-1.505f, 2.6f, 0);
They align with your native resolution but not with your skewed resolution.
That's your problem then
anyone knows why my vscode doesnt show code suggestions? like if i put inp, he would automatically go for input but he doesnt do that anymore? this is called intellisense right?
the cammel is a child of the UI
!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
if i apply the same offsets for every direction. the tiling does not match for 3 directions, the other 3 are fine
Doesn't matter, they live in completely different coordinate spaces
and what should I do to fix it?
what be the issue? it's not bouncing properly, and for whatever reason when i spawn it, it sometimes doesn't move..
void FixedUpdate()
{
Vector3 direction = transform.up;
RaycastHit2D hit = Physics2D.Raycast(transform.position, direction, MaxDistance, LayerMask.GetMask("Obstacle"));
Debug.DrawRay(transform.position, direction * MaxDistance, Color.green);
Bullet.velocity = (direction * BulletSpeed);
if(hit.collider != null){
print("Object Hit at " + hit.collider.name+ "!");
Vector2 reflectionDirection = Vector2.Reflect(direction, hit.normal);
direction = reflectionDirection;
transform.Translate(direction * Time.deltaTime * BulletSpeed);
} else {
print("Collider hit nothing :C)");
transform.Translate(direction * Time.deltaTime * BulletSpeed);
}
}
and what should I do PraetorBlue?
should i set the carpet with resolution too
like floats?
Add a debug log right after Bullet.velocity or set a breakpoint at this line to identify what bullet velocity is actually being set to. I have a feeling that BulletSpeed is zero.
@hasty sleet
I'm not sure I fully understand the issue. Is the issue that, of the six faces of a cube, your offsets only work for 3 out of 6 faces for each cube?
I recommend setting everything in the inspector because this is compatible with the canvas resizing
You might be able to programatically create/assign things to the UI in a way that is compatible with canvas rescaling, but I'm not sure how to do it off the top of my head. Some of the others might know
setting a constant world-space position will not work at all here
cant do that cause those gameobjects are being created in the script