#💻┃code-beginner
1 messages · Page 671 of 1
i dont need a new description im good
it was 😆
Anyway you seem to know that using a serialized field ref is better
If you load an additive scene and need to find one or a few objects from there its an acceptable solution to Find()
Else we usually avoid it.
if this "gamemanager script that restarted the game" is a persistent object (like being a DontDestroyOnLoad object) then it would need to find the player object each time it restarted the scene because the old player object would have been destroyed so it makes sense to use one of the Find methods there (though there are still better ways to handle it)
well then wouldnt also other refrences that playerobject has be lost?
the new player object would have the new references. of course you haven't shared the tutorial or actual code, so this information could be entirely irrelevant
What happens when we lose?
● Download the Project Files: http://devassets.com/assets/how-to-make-a-video-game/
❤️ Donate: https://www.paypal.com/donate/?hosted_button_id=VCMM2PLRRX8GU
·············································································...
my guy didnt use .CompareTag() CANCELLED
just did it with refrence object and it worked just fine
Hmm i wouldnt do what he did but it makes it easier for a beginner tutorial
no one past the beginner stage really does this so I think its all on purpose
Reminder:
tbh I dont really know his skill but he does godot now
He's decent at the engine but he's not a programmer
he's a visual artist which is why the videos usually have good production values. Programming has never really been his strong suit
Shame visual scripting was not around 8y ago as it is now.
{
Vector2 moveValue = value.Get<Vector2>();
Vector3 newPosition = new Vector3(transform.position.x + moveValue.x, 0, transform.position.y + moveValue.y);
rb.Move(newPosition, transform.rotation);
}```
Hello I'm learning the Player Input component, I tried this code to make my player move, but it always goes back to its initial position, is Move the wrong method, or am I doing vector manipulation wrong ? thank you 🙏
Don’t you have to multiply by time.deltaTime?
I don't know 😦
“When Rigidbody interpolation is enabled, Rigidbody.MovePosition creates a smooth transition between frames. Unity moves a Rigidbody in each FixedUpdate call” - scripting API
I mean if you have a velocity (your move vector) you’ll still need time for distance
am I doing vector manipulation wrong
add debugs and find out. do you know that this code is even running, how often is it running? these are things debugging will tell you
I was thinking of adding a speed variable so that it moves more smoothly but what I don't understand is why it goes back to its position before it moved
I am I just didn't include it in the sample
Debug.Log("newZ = " + transform.position.y + " + " + moveValue.y + " = " + (transform.position.y + moveValue.y));
Debug.Log(newPosition.ToString());```
Debugging will help you out
I still don't get it
part of your issue might also be that you're trying to move a rb outside of fixedupdate
input is handled every frame and not tied to the physics loop
that surprised me as well but I don't know how to do it outside the onMove callback
I’m not familiar with rbs because I like controlling behaviour more with kinematic stuff, I only heard of putting all physics in FixedUpdate, but didn’t know that input need to sync’d to FixedUpdate too
store the result of the input in a vector3. in fixed update, move the rigidbody by this vector. See if that fixes things
thank you
it's not syncing input to fixed update, input is handled by unity before the Game Logic part https://docs.unity3d.com/6000.1/Documentation/Manual/execution-order.html (the tiny Input Events part).
there are physics things you shouldnt do in update though so you need to store the input to use it in fixed update
unless there is something else wrong in the setup that i'm not seeing, I don't think much else could be going wrong here
I made the change but I get the same behavior, also since my moveVector is initialized a 0, 0, 0, the player is teleported at those coordinates, maybe Move is the wrong method ?
ive rarely seen people use .Move truthfully. though if you were going to use it, you would still add to the current position. I usually move rbs through the linearVelocity which you can try as a sanity test to see if it moves
yall i need help with this
using System.Collections.Generic;
using System.Linq;
using Unity.VisualScripting;
using UnityEngine;
public class Systematic : MonoBehaviour
{
public GameObject[] mauz;
public int indicator=0;
public ag agagag;
public PetMover pet;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
agagag = mauz[indicator].GetComponent<ag>();
if (Input.GetKeyDown("space"))
{
pet.movepoint = agagag.LocalMove;
}
if (Input.GetKeyDown("right"))
{
if (indicator < 3)
{
indicator += 1;
}
}
else if (Input.GetKeyDown("left"))
{
if (indicator > 0)
{
indicator -= 1;
}
}
if (indicator == agagag.tilevalue)
{
agagag.hoverindicator = 1;
}
else
{
agagag.hoverindicator = 0;
}
}
}
so at first i tested this in a linear way, but now that i want it to read two ints as in indicatorx and indicatory, how can i register the same object with tiles while not being able to access the list
I'm not understanding your question. Can you rephrase it?
as you can see in the script, the object selected is determined by the array's value, which is a linear number from left to right, but now i want to determine it by the selective location via an X and Y value, ill provide a vid
Use a 2d array? (or jagged array etc)
dont mind the jump, its just a wrong assigned order
but i want it to do this with Y access too
its the one wtih [,]?
it only shows numbers when i do it
wait i am mistaken, it just disappears
Multidimensional arrays are not serialized in inspector
i tried even serializing them
so i can just add them by tags?
you can't you'd need struct
what is that
I'm not entirely sure what you're trying to do but if you've got a 2d grid of objects and are wanting to map it, a 2d array should suffice. Where you'd access elements using two values (x, y etc).
Idk what ur doing lol I just replied to the thing not showing in the inspector
no as in, how to assign them, i use tags?
Assign what exactly?
the 2d array values
Like any other value =
I want them to be given in order, that seems tff
Ooo i figured it out
erm help with this
Mauz is null
That doesn't answer the question lol
wdym create?
mauz[,] = new()
oh
assigning values to an array not created will def give you null ref
i never knew i had to do that
you should most definitely do some c# basics first, there are resources pinned in the channel
for normal arrays
i used them and didnt create it
This isn't specific to arrays but any reference type
oh
Exception unity Objects but those are special
also normally unity creates object for you if you serialize it in the inspector like a regular poco/object (arrays is a good example)
🤷♂️ up to you, but you also seemingly have never seen a null error before. you can struggle through the c# part all you want while trying to learn unity too. it wont be fun
all roads lead to rome
You can't travel the road if you don't know how to walk
or as we've seen lots of times, beginners who give up because their code "stops working" and isn't possible to fix without rewriting everything. 6 months of duct taping and awful coding habits isnt sustainable. willpower wont create your game
I am taking computer science in college, so in no planet ill lose intrest
computer science isn't always synonymous with specific language coding
Plenty of compsci graduates who never coded a thing to save their life lol
For clarity, a null reference exception error occurs when you attempt to access a member (get component function in your case) from something that is null and not the thing we're trying to actually get (what we're trying to get can be null and it would be fine). So if a had a field named b and b had a field named c and c had a function named D..
If an nre had occurred when trying to:
access b, we can assume that a was nullcs var t = a.b;//nre if a was nullsame applies for the remainder:cs t = a.b.c;//nre if a or b were null t = a.b.c.D();//nre if a, b or c were nullIf we were to only access a, it would not throw an error during assignment as a being null is valid (you just might get errors later if you ever attempt to access a member of t):cs t = a;//no error even if a is null t.b = z;//nre: t was null but we're attempting to access the member b
ik what null is, i just didnt read the error 🔥
My brain is being dumb this morning. I've got a list of world positions that i want to make a bounds out of. I know i can get the average position for the center but how do i calculate size?
oh can i just make a empty bounds and encapsulate them all?
Bounds out of?
If you know the centre then it would be faster to find the furthest point and then encapsulate just it.
Just keep calling https://docs.unity3d.com/2022.3/Documentation/ScriptReference/Bounds.Encapsulate.html on them all
Depending on the size of his point cloud that could get expensive
heard ty both
hello @everyone, i am creating a 3d chess game, and rn i am only at the beginning, and i am trying to, when i hover my cursor on a tile (that i created via script) it changes layer, like from( tile ) to (hover) and then comes back to (tile) when i remove my cursor from that tile. My problem now is that it isnt working even tho i got no console error and i think that my script is good. Maybe i need to add something to it idk: here is the part of my script:
private void Update()
{
if (!currentCamera || !boardActive //IS A BOOLIAN)
{
currentCamera = Camera.main;
return;
}
RaycastHit info;
Ray ray = currentCamera.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out info, 100, LayerMask.GetMask("Tile", "Hover")))
{
//GET THE INDEXESOF THE TILE I'VE HIT
Vector2Int hitPosition = LookUpTileIndex(info.transform.gameObject);
//IF WE'RE HOVERING A TILE AFTER NOT HOVERING ANY TILE
if (currentHover == -Vector2Int.one)
{
currentHover = hitPosition;
tiles[hitPosition.x, hitPosition.y].layer = LayerMask.NameToLayer("Hover");
}
//IF WE WERE ALREADY HOVERING A TILE, CHANGE THE PREVIOUS ONE
if (currentHover != hitPosition)
{
tiles[currentHover.x, currentHover.y].layer = LayerMask.NameToLayer("Tile");
currentHover = hitPosition;
tiles[hitPosition.x, hitPosition.y].layer = LayerMask.NameToLayer("Hover");
}
}
else
{
if (currentHover != -Vector2Int.one)
{
tiles[currentHover.x, currentHover.y].layer = LayerMask.NameToLayer("Tile");
currentHover = -Vector2Int.one;
}
}
}
pls answer i am desperate
lol, don't at everyone 🤦♂️
And use the !code tags to display it properly 👇
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
your code looks like AI code.
Also, for a start - this will give a compile error
if (!currentCamera || !boardActive //IS A BOOLIAN)
I created code to instantiate a bullet prefab, but how can I make a custom rotation for it? right now, it spawns according to this player rotation, which is horizontal, but I want it to be vertical.
public class shootTest : MonoBehaviour
{
[SerializeField] private GameObject bulletPrefab;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
Instantiate(bulletPrefab, transform.position, transform.rotation);
}
}}
not sure I did that right
Instead of using the player rotation when instantiating, use whatever rotation you want
you did not, use 3x `
Instantiate(bulletPrefab, transform.position, **theRotationYouWantItToBe**);
I'm probably doing this wrong, but now it's saying that no overload for instantiate takes 5 arguments
Yes because you just added 3 zeroes instead of a rotation
yea, I'm super confused on how it should be set out
it needs a quaternion (as the hover message shows), not 3 euler angles or whatever you've tried to set there
You can do something like Quaternion.Euler(0, 0, 0) to get a rotation
also why do you want a bullet to be vertical if you're presumably trying to shoot it
but if this is confusing it might be best to go through !learn beginner courses again
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Hello guys. I want to make a circle like this. And I want it to be Collider sensitive. How can I do that?
just looks better, I'm fine if I can't get it to work (not the end of the world), but it'd look nice
a bullet being vertical looks better than a bullet actually pointing in the direction of travel?
is your mesh misaligned or something?
you add a collider
If you're not doing this by code, you're in the wrong channel.. delete and ask in #🖼️┃2d-tools
Wow super clever man how can i forgot about it
Sorry, thanks for help
vertical as in it goes in the direction of the barrel
that would be horizontal
or do you mean when looking up?
sounds like you'd want the rotation of the camera, not the player
game is in top down view, I may be getting my words mixed up
yeah you definitely need to give more context here
what exactly is the issue you're having?
put an empty transform as a child of the gun. Rotate it so that the Z forward is pointing along the barrel of the gun and at the end of it.
Spawn the bullet at the same pos/ rotation as this transform.
err... might not be Z forward on top down... X instead?
that probably would have made my life much easier, I just made the gun a part of the player sprite
the gun can remain part of the player sprite
this worked, thnx for the help
public GameObject gun;
public GameObject bulletPrefab;
public void Shoot()
{
GameObject spawnedBullet = Instantiate(bulletPrefab);
spawnedBullet.transform.forward = gun.transform.forward;
}
//Or if your game is top-down
public void Shoot()
{
GameObject spawnedBullet = Instantiate(bulletPrefab);
spawnedBullet.transform.up= gun.transform.up;
}
try to do this
don't use public fields
assign the position and rotation when instantiating, not on a separate line
that won't even set the position
Every time I do this, it works. What is the problem with tihs?
please don't spoonfeed
I am just talking about the rotation
it's not that it doesn't work, but if you get recommendations, you'd want them to be good recommendations, right
If he dont know the meaning of the code he can basically ask
Yeah but fixing the rotation isn't very useful if the solution breaks setting the position
and spoonfeeding discourages that
It works, but it's bad/ beginner code.
You don't want public fields, because nothing outside of this class should have direct access to those fields, if you want them visible in the inspector use [SerializeField] private <type> myVariable;
The instantiate method has overloads, specifically for setting the position and rotation when you spawn the object, so it can be put in the correct position / rotation (etc for the other overloads), and not spawn at 0,0,0 then jump to whatever position and rotation you set after spawning it.
i am creating a 3d chess game, and rn i am only at the beginning, and i am trying to, when i hover my cursor on a tile (that i created via script) it changes layer, like from( tile ) to (hover) and then comes back to (tile) when i remove my cursor from that tile. My problem now is that it isnt working even tho i got no console error and i think that my script is good. Maybe i need to add something to it idk
private void Update()
{
if (!currentCamera || !boardActive //IS A BOOLIAN)
{
currentCamera = Camera.main;
return;
}
RaycastHit info;
Ray ray = currentCamera.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out info, 100, LayerMask.GetMask("Tile", "Hover")))
{
//GET THE INDEXESOF THE TILE I'VE HIT
Vector2Int hitPosition = LookUpTileIndex(info.transform.gameObject);
//IF WE'RE HOVERING A TILE AFTER NOT HOVERING ANY TILE
if (currentHover == -Vector2Int.one)
{
currentHover = hitPosition;
tiles[hitPosition.x, hitPosition.y].layer = LayerMask.NameToLayer("Hover");
}
//IF WE WERE ALREADY HOVERING A TILE, CHANGE THE PREVIOUS ONE
if (currentHover != hitPosition)
{
tiles[currentHover.x, currentHover.y].layer = LayerMask.NameToLayer("Tile");
currentHover = hitPosition;
tiles[hitPosition.x, hitPosition.y].layer = LayerMask.NameToLayer("Hover");
}
}
else
{
if (currentHover != -Vector2Int.one)
{
tiles[currentHover.x, currentHover.y].layer = LayerMask.NameToLayer("Tile");
currentHover = -Vector2Int.one;
}
}
}
https://docs.unity3d.com/6000.1/Documentation/ScriptReference/Debug.Log.html
Start getting acquainted with logging to the console
i dont want something to happen when i click but something to happen when i ONLY put my cursor on the game object
its really curious how u dont have errors.. when the script u sent is broken
i just added it when i was sending you the script
we can tell it's a boolean by the way it's used in an if
only cuz i didnt send
private bool boardActive;
.....
or use a /* boolean */ block comment
you can tell by the way that it is.. 😂
🌲 humor
how do i do it
the boolean knows where it is because it knows where it isn't
if (!currentCamera || !boardActive) //like this
{
currentCamera = Camera.main;
return;
}```or
```cs
if (!currentCamera || !boardActive /* like this */)
{
currentCamera = Camera.main;
return;
}```
ok wait a sec
that clears up the compile error u may or may not have. (unsure)
but that doesn't solve ur main issue (unless it does)
u need to use some log statements
how exactly isn't it working? is it not hovering? is it not going back?
when i hover my cursor on the game object
put them in ur raycast see if its hitting anything/ what its hitting/ when its not hitting
the layer doenst change i put my cursor on the tile even tho it should
i can send the entire code if you guys want but the rest is all about generating the tiles
put some logs - is the raycast being reached, is it passing, is some other conditional not passing?
etc
if (Physics.Raycast(ray, out RaycastHit info, 100f, LayerMask.GetMask("Tile", "Hover")))
{
Debug.Log("Raycast HIT: " + info.transform.name + " on layer: " + LayerMask.LayerToName(info.transform.gameObject.layer));
...
}
else
{
Debug.Log("Raycast MISS");
}```
u can log when u change the layer to confirm that happens..
so on and so on the more u know the better
im guessing its probably a layer / mask issue
for example is the tile actually on the tile layer...
(like if the collider was a child object) it could be missin
yea i tried it but the console says that the hitPosition does not exist
absolutly everything is made in the script
the tile the collider etc
Vector2Int hitPosition = LookUpTileIndex(info.transform.gameObject); possibly this is broken somehow then
or in the LookUpTile function
send logs to urself in those methods and see if its outputting what it should
private Vector2Int LookUpTileIndex(GameObject hitInfo)
{
for (int x = 0; x < TILE_COUNT_X; x++)
for (int y = 0; y < TILE_COUNT_Y; y++)
if (tiles[x, y] == hitInfo)
return new Vector2Int(x, y);
return -Vector2Int.one; // -1 -1
}
for hitboxes in my game with timestop, is it better if I store the hit and apply the effects after time has been resumed or if I instansiate a collisionbox alongside my Visual Effect object
show a screenshot of one of the tiles selected in play-mode and its inspector visible
k wait
what type of problems are u expecting to avoid by using one over the other?
what concerns do u have to be debating the two?
well, i see the problem
which is?
like an invisble line
whats it hitting do you know?
a raycast hits a collider
ur tiles have no collider
so.. no raycast can ever detect them
Vector2Int hitPosition = LookUpTileIndex(info.transform.gameObject);
to this maybe?
Vector2Int hitPosition = LookUpTileIndex(info.collider.gameObject);
thats using the info variable..
which is hit info the raycast outputs
but thats if the raycast detects a collider...
ur raycast is never hitting any of those tiles
u dont need to change ur code.. u need to fix ur tiles
so i need to change info to hitInfo?
do i send you the tile generation code?
for using a boxcast mostly to save resources and not needing to spawn a collision box, for spawning hitboxes it's for better interactions (e.g. when I want to have things moving in timestop as a mechanic)
I'm thinking of if using a boxcast will make my life easier because registrating the hit while the VFX is still playing is fine, any onhit effect I can delay them until after time has resumed
i dont even have a collider in my tiles
ya, thats the problem
wait a sec
i went to my code and i saw this:
tileObject.GetComponent<BoxCollider>();
i fixed it
tileObject.AddComponent<BoxCollider>();
but it still doesnt work
if time truely stops for everything i feel raycasting could be easier and cleaner
if not and theres reasons to have immediate hit detections /visual feedback id do the latter
well no go back in the game- run it and see if they have colliders
they do
then add logs in ur raycast to see if ur hitting them..
it doesnt really matter..
I'm thinking of making some bosses ignore timestop for the funnies
ok thx
but realistically I don't have time for it before I need to push this out for my profolio entry for uni
you'll just want to Log the hit variable of ur raycast
and even put one in the if and the else Raycast succeeded Raycast Failed
for a second I thought you were responding to me lol
look man i am not a pro at this just a beginner
i understand that.. and these are the most basics of concepts..
logging is 1 of the first things u should learn
also a question on this: is physics.raycast not instant?
it occurs on the next physics frame (FixedUpdate()) i believe
edit: my mistake.. Physics "Raycasts" are just checks not physics-driven forces or any of the like..
therefor they are practically "instant".. If you call a raycast in update it'll run a check every frame
I feel like the latter will be better then, gives more control over behaviour
can you send all the refenreces for like: rayDistance queryTriggerInteraction, etc
if (Physics.Raycast(ray, out info, 100, LayerMask.GetMask("Tile", "Hover")))
{
Debug.Log("Raycast succeeded");
Debug.Log(info.transform.name);
// GET THE INDEXES OF THE TILE I'VE HIT
Vector2Int hitPosition = LookUpTileIndex(info.transform.gameObject);
Debug.Log(hitPosition);
...
}
else
{
Debug.Log("Raycast failed");
...
}```
https://gamedevbeginner.com/how-to-use-debug-log-in-unity-without-affecting-performance/
no, you already have ur raycast written out. its simple as putting LOGS inside what u have..
and see if it runs.. and if it doesn't.. if it does u send info thats useful to figure out what in the code isnt returning the results ur expecting.. or running at all)
ya, i use raycasts for everything so im a bit biased
but the collider method sounds fine too
absolutly nothing works
i feel like my brain wants to implode
i am about to give up on this project
i personally feel like u bit off more than u can chew.. and need to take a step back..
for example first writing a simple raycast.. have it hit a cube directly in front of it.. see what works and what doesnt.. log that information in the console.. take in, take notes, then u grow.. expand.. and add more and more slowly
how do you exclude all collision layers except one for colliders? When initiated do they default to collide all or no layers?
well once u had it working with a cube.. u coulda made it work with a tile
once u had it working with a tile.. u could add in the layers..
to took me more than a morning to even comprehend the input system lol chill
so and so on.. my point still stands.. ur biting off more than u can chew.. and resolving ur issue is going to be more frustrating for you and the helper than needs be..
im being generous too. most other guys will just send you the !learn links and tell you to go back to the basics
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Read documentation it helps a lot
imma try again
for example i bet u unity has tile systems as examples in their documentation
also this 
Unity’s tile stuff is kinda mid for what most beginners will want
they all get the (tile) layer
What do you mean by this
Not a question for this channel.. but, a collider uses the layer of the gameobject to know what it can collide with. You set which layers can collider in the collision matrix
oh sorry that was me asking a question lol
oh mb, could you redirect me to which channel I should ask in so I know next time?
{
Physics.BoxCast(
center: castCenter,
halfExtents: vector3HalfExtents,
direction: slashDirection,
hitInfo: out _meleeHitRegister
);
return;
}``` bit of a stupid question: is this correct syntax?
does returning this gives a boolean?
If your IDE is setup correctly, it will tell you of any compile / syntax errors.
you're not returning anything there.
void - means the method doesn't return anything, so your return at the end there does nothing, removing it and you're doing the same thing.
ah, any reason why it's void instead of a bool like it's supposed to?
because your wrote it like that?
It does.
You are not doing anything with that bool.
I just want to store it
you have the documentation open, the documentation has example code
bool b = BoxCast()
If you’re trying to return the Physics.BoxCast(…) then change the return type from void to bool and say return Physics.BoxCast(…)
ah ok this makes sense
https://streamable.com/6jc4km here's a vid clip i made laying out the process you probably need to take..
- make simple raycast, raycasting using mouse position and main camera (test and confirm)
- make tile prefab setup to work w/ raycast (collider and layer assignment) (test and confirm)
- simply use the raycast overload that can accept a layermask, assign the 'Tile' layer or w/e layer u chose for the tiles to this layermask in the inspector (test and confirm)
if u stop and test along the way you end up with smaller problems with easier solutions..
than if u wait until the end and realize it doesn't work.. but unsure why or how it became that way
Is anyone free to help troubleshoot an object interaction?
In my player controller script I have:
Getting these debug messages
{
playerInteraction.TryInteract();
Debug.Log("Interact action performed");
}
Getting these debug messages as well
using UnityEngine;
public class PlayerInteraction : MonoBehaviour
{
Transform _transform;
[SerializeField] LayerMask interactableLayer;
void Awake()
{
_transform = transform;
}
public void TryInteract()
{
Debug.Log("Attempting to interact...");
if (!Physics.Raycast(_transform.position + (Vector3.up * 0.3f) + (_transform.forward * 0.2f),
_transform.forward, out RaycastHit hit, 3f, interactableLayer)) return;
}
}
For some reason I'm not getting anymore debug messages: My SingleDoorControl script
using UnityEngine.Events;
public class SingleDoorControl : MonoBehaviour, IInteractable
{
private Animator animator;
private bool isOpen = false;
private bool openedForward = false;
[SerializeField] private Transform playerTransform;
[SerializeField] private Transform doorForwardReference;
void Awake()
{
animator = GetComponent<Animator>();
}
public void Interact()
{
if (!isOpen)
{
Debug.Log("Door was open and tried to open");
Vector3 toPlayer = (playerTransform.position - transform.position).normalized;
float dot = Vector3.Dot(doorForwardReference.forward, toPlayer);
if (dot >= 0)
{
animator.Play("SingleDoorOpen_Backward");
openedForward = false;
}
else
{
animator.Play("SingleDoorOpen_Forward");
openedForward = true;
}
isOpen = true;
}
else
{
if (openedForward)
animator.Play("SingleDoorClose_Forward");
else
animator.Play("SingleDoorClose_Backward");
isOpen = false;
}
}
}
My interactable object and iinteractable scripts:
using UnityEngine;
using UnityEngine.Events;
public class InteractableObject : MonoBehaviour, IInteractable
{
[SerializeField] private UnityEvent _onInteract;
public void Interact()
{
Debug.Log($"Interacted with {gameObject.name}");
_onInteract.Invoke();
}
}
using UnityEngine;
using UnityEngine.Events;
public interface IInteractable
{
// public UnityEvent Interact { get; protected set; }
public void Interact()
{
Debug.Log("Interact method called on IInteractable");
}
}
My player and door have the following components:
Let me know if there is anything else I can provide that would be helpful 🙂
I'm thinking the problem might lie somewhere on my player interaction script. Maybe it's not called the Interact right?
Door is on the intractable layer
you say you don't get any logs, and then the next code block doesn't have any logs in it
I mean, you don't do anything in TryInteract(), you either return or do nothing
your PlayerInteraction class doesn't actually call any interaction.. it's just raycasting looking for an interactable layer
Ahh you're right Gruhlum, I added a debug message inside this method and I do see the debug message in the console:
public void TryInteract()
{
Debug.Log("Attempting to interact...");
if (!Physics.Raycast(_transform.position + (Vector3.up * 0.3f) + (_transform.forward * 0.2f),
_transform.forward, out RaycastHit hit, 3f, interactableLayer))
{
Debug.Log("No interactable object found in range.");
return;
}
else
{
return;
}
}
right.. but you're not doing anything... you're not getting the component to call the interact method on it. Methods don't run if you don't call them.
see if "hit" has a Component of Type IInteractable and then call Interact() on that component
Something like this?
public class PlayerInteraction : MonoBehaviour
{
Transform _transform;
[SerializeField] LayerMask interactableLayer;
void Awake()
{
_transform = transform;
}
public void TryInteract()
{
Debug.Log("Attempting to interact...");
if (!Physics.Raycast(_transform.position + (Vector3.up * 0.3f) + (_transform.forward * 0.2f),
_transform.forward, out RaycastHit hit, 3f, interactableLayer))
{
Debug.Log("No interactable object found in range.");
return;
}
// Get the IInteractable component and call Interact()
var interactable = hit.collider.GetComponent<IInteractable>();
if (interactable != null)
{
interactable.Interact();
Debug.Log("Interact called on: " + hit.collider.name);
}
else
{
Debug.Log("Hit object is not interactable: " + hit.collider.name);
}
}
}
Just tested and only getting to the attempting to interact debug message
void Update()
{
ray = new Ray(cam.transform.position,cam.transform.forward);
if(Physics.Raycast(ray,out RaycastHit hit,distance,mask))
{
if(hit.collider.TryGetComponent(out IInteractable interactable))
{
cachedInteractable = interactable;
cachedTransform = hit.transform;
cachedHitPoint = hit.point;
if(Input.GetKeyDown(interactKey))
{
cachedInteractable.Interact();
Dbug.Italic($"Interacted with {cachedTransform.name}");
}
}
else
{
ClearCache();
}
draw = true;
}
else
{
ClearCache();
draw = false;
}
}``` heres how mine looks if it helps any..
if you don't see "No interactable object found in range." than that means that you found an object but it doesn't have an IInteractable Component
i also log the cachedTransform in the inspector.. makes me feel better for some reason lol
raycast must fail then no?
well, something isn't right tho, because you should either way get one more Debug massage
-check layermask
-check ur actual raycasting position and direction
-check that the object is in range and not blocked by something else
-check that the object has a collider and its not on a child or something else
do what i did ^ and just log the hit info in the console or inspector at first.. make sure its detecting the thing that has the component..
and that u dont have to retrieve it from up or down its hiearchy
So on my player gameobject, I changed the player interaction serialized field to Player Interactio and the door is opening now. Originally I had this set to playerinteractionmanager. Is it better to try and set unity events up in a manager? Sorry if this question is badly worded. Just started learning how to set up more scalable unity events yesterday..
whats your goal?
Visual view:
to open a door?
Honestly to have a system that makes it easier to add future events like picking up object, throwing things, interacting with different object with different results, etc
well the goal would be bigger than that. if they're doing an Interactable Interface
instead of events i'd recommend interfaces then
interfaces are perfect for this
you make an IInteractable interface
and objects that are interactable can have different behaviours
ya, interfaces w/ trygets is my jam 🪕
I'll have to look into interfaces. What were y'alls favorite resources while learning how to use them?
tbh interfaces were trial and error + friends help
basically its just this tho
and then anything that inherits just has to have that Interact() method
and for a pickup:
Then you just have a super long switch statement? Somethign that has all the interactions?
well the switch is only b/c my switch class can function 3 different ways
like toggle, push to start, etc
ahh, nice
u just call the function with the Interactable Raycaster or w/e
my raycast doesn't really care if its a pickup, a switch, any kind of action..
it only has to call .Interact()
What confuses me the most is when linking interact() with the method that does the action. I feel like seeing Interact() everywhere confuses me but I like the benefit lol
if its an IInteractable -> then it must have an Interact() method..
if it has an Interact() method.. i'll just call it.. theInteractableYouHaveSelected.Interact();
The class implementing the interactable interface handles the interaction. Interfaces are specifically to avoid having one giant method handling every single interaction
public class TunaCan : MonoBehaviour, ICollectible
{
[SerializeField] PlayerController playerController = null;
[SerializeField] bool isMovingToPlayer;
[SerializeField] bool isCollected;
public static event Action OnCollectTunaCan;
// Update is called once per frame
void Update()
{
if (isMovingToPlayer)
{
transform.position = Vector3.MoveTowards(transform.position, playerController.transform.position, UnityEngine.Random.Range(0.1f, 0.2f));
}
}
public void Collect(PlayerController playerController)
{
this.playerController = playerController;
isMovingToPlayer = true;
}
my code is simpler
using UnityEngine;
public class Collect : MonoBehaviour
{
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Collectible"))
{
PlayerController playerController = GetComponentInParent<PlayerController>();
ICollectible collectible = other.GetComponent<ICollectible>();
collectible.Collect(playerController);
}
}
}
then just a lil script that calls that interface
Could you use that Collect class on an any gameObject you want to be collected?
yea thats the idea
for me anything that is tagged Collectible will have a ICollectible interface
that i can do whatever i want with
🎮 easymode:```cs
if (hitObject.CompareTag("Pickup"))
hitObject.GetComponent<Pickup>().DoPickup();
else if (hitObject.CompareTag("Switch"))
hitObject.GetComponent<Switch>().Toggle();
else if (hitObject.name.Contains("Lever"))
hitObject.GetComponent<Lever>().Activate();
🕹️ skilled-mode:```cs
if (hit.collider.TryGetComponent(out IInteractable interactable))
{
interactable.Interact();
}```
in this case collect
it seems a bit weird at first but its one of the most powerful ways of not repeating your code
Do you have an interactable layer as well? Are your collectibles on that interactable layer if you do?
no thats the cool thing about them..
nope
just a Collectible tag and when player goes over them boom
magic
the fact this script has a Switch that inherits from IInteractable
my raycast just grabs it
i even use Interfaces as tags sometimes
well actually i just use an empty script
but same idea
arent you hitting any collider and checking if for IInteractable all the time?
well my raycast does raycast all the time yea
but the tryget fails if its not an Interactable
so none of that logic gets run
just a bit weird, why not put those IInteractable objects in a layer?
For systems like this its better if you implement it yourself rather than trying to copy what someone else did. You might want interactions to happen in a different way first off compared to OnTriggerEnter. A lot of people also dont like tags all that much and would rather use layers
otherwise you're looking at anything and checking for IInteractable constantly
Pretty common and isn't really a problem (I do this in every project that wants interactions).
and i can have more than 1 interface on a Gameobject 😉
ya, for basic games 1 or 2 is enough for Interactions
Is it better to have an interface system when working with inventory systems?
definitely
I just don't use tags because something can only have 1 tag, which limits their usefulness
My interactables have a separate object with the trigger collider that exists on an Interactable layer, just for raycasting. But the parent object can be on any layer.
you see it with minecraft
some objects arent stackable
interfaces are pretty good for that type of stuff
Interfaces unravel OOP inheritance into something more sane
yea was honestly one of the best things to learn
the code in general gets so much cleaner
are scriptable objects another thing to learn as well? I honestly don't know much about interfaces or scriptables object..yet
yup
just remember to only store static data in them
they dont save during runtime
Absolutely, they are very handy as data containers and for compartmentalizing some methods, like RPG skills
They can also be used for logic in a way you can share easily over many scenes but its easy for it to get unloaded so duplicate instances may be made accidently.
That makes sense, maybe it's better to use raycasting instead? Also I just did some research and it looks like using layers might offer performance benefits by excluding certain objects from raycast or collision checks using layer masks
All the skills, stats, spells, items, traits, monster setups, dialogue, and many other bits of data are scriptable objects in my game
you can ask this about any concept in c# and someone will chime in with "it wont hurt to learn". dont get overwhelmed trying to learn everything. look at scriptable objects when you need them. They are just simply data containers.
i wouldnt worry about performance in the beginning
just make things work
you mean immutable data hopefully, static would mean the static keyword
yea my bad
The chances of actually noticing bad performance in your game when starting out is pretty negligible. By the time you're doing stuff that hurts performance, you'll have the experience needed to tackle it
Ahh thanks, that means I'd have to reload my domain on play because I've heard from somewhere that if you don't reload your domain your static variables won't change or something
thats different
my point is if you try to save data into a scriptable object the next time you run your game its gone
(except in editor where its kept cus dumb)
I feel like my overwhelmed feeling just turns to excitment because it's another area to learn about this stuff😂
yes people often use layers here so you arent trying to get a component (the interface) on every single object. You would use a raycast if you wanted to interact by looking at an object or having your mouse over it
That's a positive sign you'll enjoy the journey
i cant imagine the pain and suffering of the people that found this out when their game was ready to ship
Ha yea, it annoys me more when I want to change a serialized var and i dont expect it to be 'saved'
I was watching a video where it caused issues like incorrect save location
Unity should fix scriptable objects keeping the changes post play to make it clearer its not a thing
surely it can just re apply the saved data after
If my scriptable object's state is being changed in game, I store a separate value on it which is the Current value. The current value is set to be the same as the initial saved value, and then only the Current one gets modified.
that doesnt really make sense by itself. though still, didnt you want to be looking at interfaces for now?
this could honestly be a feature for a horror game
you change the spawn location var in the SO, next time you reload the game you're at the beginning
Yeah I got some tutorials and guides to read up on
just make sure to take your time
making games is super hard
its normal to get overwhelmed
you'll likely learn this quicker outside of unity tbh. if you've done your c# basics first then itll be no problem. Find any tutorial that talks about some animals interface, then makes a cat dog and puts them all in the same array and boom its solved. Then try to extend that to your own kind of class
there isnt much to learn about interfaces
Yeah right now I just have dev_playground project and I'm just tackling random things like making doors open both way or picking up cubes. If I need a quick idea I usually just as AI for something to build out. Once I found out how much goes into player movement it made me appreciate games a LOT more becuase players don't see what makes a game, a game
yea that goes with most industries
It's not dumb, and makes sense. In the editor, if you don't instance the SO before modifying it, then you are directly modifying the asset itself. In a built game it basically just loads the SO from the game's resources each time you boot the game, which doesn't change since there are no "assets" anymore.
once you start diving into it you realize how deep the rabbit hole goes
I know, which is why unity adding a mitigation would be a good idea
It never ends haha. When you think it does the next editor verison comes out..
even if there weren't any new releases from now on.. it'd be unlikely u'd still know everything there is to know
and theres some things u never need to know..
im building a 3D game.. i don't need to know how the tilemap system works
only master nerds know everything bout the entire engine 😈
One of my goals is to get suuuper good at unity so that by the time Unity 7 alpha gets released (late 2026 or 2027), I can start making guides on how to use it and hopefully even a course. That was one of my biggest OCD complaints when learning because I'd be on unity 6 but the guide was using 2019. Even those there should be compatibilities, just having a guide that uses the version your on is just helpful. Making a course would also hopefully expose me to Unity areas I hadn't seen before so it's another reason I'd want to tackle something like that.
I built a 2d brick breaker game using assets I made from Aseprite to learn how to integrate the two. Was a fun little project that didn't take too long. Also helped with learning about asset scaling
Also @simple hawk any luck on learning the new input system? This was a really helpful video that I used to help learn the system. After watching the tutorial I first studied how each part connected to eachother and then I just kept trying to make my own input system basic control scheme from scratch until I could make it without really needing to glance at the completed code:
https://www.youtube.com/watch?v=Yjee_e4fICc&t=60s
ok so i have an enemy that i want to stop moving for a bit every now and then, i already got the logic for when it stops moving, to wait a bit before mvoing again, but for stopping movement, can i just start such a coroutine inside start()?
private IEnumerator ResetWalkWaitTimer(float wait)
{
yield return new WaitForSeconds(wait);
float delay = Random.Range(5f, 10f);
waitBeforeWalkTimer = 0f;
StartCoroutine(ResetWalkWaitTimer(delay));
}
you can just use a while loop tbh
and probably even make Start itself the coroutine (unless you call ResetWalkWaitTimer at later time)
Hi, what would be better for move a dynamic rigid object to follow another actor and to move side to side
linearvelocity or addforce?
also, how i can make an int of a script be private but only be accesible for the children of that script? When i make it privated its childrens can't interact with it
wdym by "children of that script"
are you talking about inheritance or components in other gameobjects
also linearvelocity or addforce both move the rigidbody properly, addforce takes mass/friction other physics attributes into account, velocity doesn't
i just want it to walk, without phasing thought physics
and i mean inheritance, i forgot the word in english for heredero wich is inheritance i think, thanks
yeah, inheritance
nop, my english is bad, is not heredero, is herencia, but yeah, that thing is
check the link posted above , you can use protected or private protected
ooh, interesting, thanks :3
what about rb2d.MovePosition?
i just want it to chase an object without glitching or phasing tru walls
then don't use MovePosition, its meant for kinematic movement and will def phase through walls
got it, so i should use linearvelocity or i should use addforce? i mean wich one would be cleaner
idk what you mean "cleaner" I kinda already pointed out the differences, see which one fits your need
they are both good methods, different "feel"
I think velocity is simplier. Cuz i dont need friction and others to be calculed, thanks :3
how i can fuse functions between inherites?
I mean, i have that in the baseScript update it flips depending on a value transform.localScale = new Vector3(-1, 1, 0); , and i want the InheritedScript update to do the same and play an animation clip animator.Play("Base Layer.MortemRifleSight"); but without having to write the flipping part that belongs to the base, how i can do so?
i know how to replace, using overdrive, but i dont know how to fuse
you mean override?
you can call the base method with base.Method
class A {
public virtual void Print() {
print("A");
}
}
class B : A {
public override void Print() {
base.Print();
print("B");
}
}
new B().Print(); // prints `A` then `B`
Yeah if you have that in Update, Unity won't call the base class' Update so you have to do it yourself by making it virtual and calling it from the override
General question here. If I have two variables (int type) that are set to different values and I write an equality statement such as
numberA = numberB
does numberA get set to the value of numberB or vise versa? Basically which order does Unity use?
ooooh, thanks
i was replacing my old enemy movement with a new one that uses their rigidbodies....but i discovered an issue.........................why my enemies fly?
mortemRb.linearVelocity = direction * runSpeed;```
that's not an equality statement in the programming world, btw - that's an assignment, and it's always "set x to y" for some x = y
field initializers use the same syntax - float speed = 8 or whatever
ah yeah makes sense thanks
it's analogous to := in math, as in x := y -> "let x be equal to y"
some languages use := for assignment, but most just use =
i dont get why they fly
are you doing sidescroller or top-down?
Are you using AddForce? What does the code look like
mortemRb.linearVelocity = new Vector2(direction.x * runSpeed, mortemRb.linearVelocity.y);```
now i fix it
they no longer fly
ths was the bad script
mortemRb.linearVelocity = direction * runSpeed;```
yeah thought so
but, now i have another problem
though this means it'll run slower if they aren't at the same elevation
instead of normalizing the vector, you'd want to normalize just the x value
you can use Mathf.Sign/Math.Sign for that (depending on what you want to happen if they're perfectly inline vertically)
Is there a way to exclude a single item when using Random.Range to select from an array? I have a string array (six individual letters of the alphabet) and I'm trying to randomly generate one after the other without repeating the previous letter that was generated. I tried assigning a "lastMove" integer to the last array item that was picked and checking if the current item number matches the "lastMove" number using an if/else statement but this doesn't work if the random number is identical twice in a row. Any ideas would be appreciated.
here is the script if needed. Useless context: it's a Rubik's Cube random scramble generator and I'm trying to generate 20 random letters consecutively (each letter in the array stands for turning a certain face on the cube).
public class NewScramble : MonoBehaviour
{
public TextMeshProUGUI scramble;
private string[] possibleMoves = {"R", "L", "U", "D", "F", "B"};
private string[] moves = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
"11", "12", "13", "14", "15", "16", "17", "18", "19", "20"};
private int moveSelector;
private int lastMove;
void Start()
{
GenerateNewScramble();
}
public void SelectNextMove()
{
moveSelector = Random.Range(0, possibleMoves.Length);
}
public void GenerateNewScramble()
{
SelectNextMove();
lastMove = moveSelector;
moves[0] = possibleMoves[moveSelector];
SelectNextMove();
if (moveSelector == lastMove)
{
SelectNextMove();
lastMove= moveSelector;
moves[1] = possibleMoves[moveSelector];
}
else
{
lastMove = moveSelector;
moves[1] = possibleMoves[moveSelector];
}
}
}
The text object reference hasn't been used yet because I'm trying to figure out this part first
well you want to keep going until you get something that isn't the previous move, right?
that'd be a loop, not a conditional
the correct way to do this is to put them in a list or array and shuffle it, then iterate over the shuffled items
also, i made an if statement that if the distance is less than x value, it should stop, it worked when i used the transform.position, but not with the rigidbody
{
if (distanciaAbsoluta > rangoDisparo)
{
animator.Play("Base Layer.MRifle_Walk");
Vector2 direction = (objetivo.position - transform.position).normalized;
mortemRb.linearVelocity = direction * runSpeed;
bullettimer -= Time.deltaTime;
if (bullettimer <= 0)
{
bullettimer = firingspeed;
disparar();
}
}
else
{
bullettimer -= Time.deltaTime;
if (bullettimer <= 0)
{
bullettimer = firingspeed;
disparar();
}
}
}```
this wouldn't really work for the usecase though
yes. I thought of that but I didn't know if that was possible (I'm not very experienced in coding lol)
maybe I don't understand the use case
a loop is like the very next step up from a conditional
I can't repeat the same letter twice in a row
you might want to step back and learn about programming fundamentals first rather than stumbling through code
see pinned resources
sorry I misspoke. I know what a loop is but I didn't know a way to implement it in C#
it's not just shuffling the various moves, the output length should be able to be greater than 6
then you should go find out how to do it in c#, see pinned resources
additionally - with how you've written it, you can't get R as the first move, you should probably check that
I don't know anything about rubik's cubes so I don't understand what the goal is here really
so I'll back off
how i do that?... But also... isn't that how it should work? i mean, they slow when im up of them, cuz is like i were in the middle of them, or how?
i dont know, i just want them to chase the player and feel nice, but only chase it until the distance is x
also you probably should not have that moves array literal, you can just do new string[20] for an empty array
but a list would probably make it much easier
the goal is to shuffle the cube with a random sequence of moves, rather than shuffling the sequence of moves
i have no idea what you're trying to say in that first sentence
@vocal wharf this was intended for you btw, in case you missed it
mmm
i dont get, what happens if im higher?
i got lost
but anyways i feel like this might be more important
in these 3 scenarios, should the chase speed be the same
oh now i get it, i guess it will
sorry
so...how i can fix this?
(i fixed the radius issue, i just had to put mortemRb.linearVelocity = Vector2.zero)
if you normalize the entire vector and then get just the x value, the x value's magnitude will be <= 1
you'd want it to be == 1 for a consistent speed, regardless of vertical offset
the moves array is intended to be exactly 20 moves long every time and I'm trying to randomly assign a letter to each item in that array (without repeating a letter twice) and display those letters on screen with a text object. The only point of the moves array is to make things simpler so I can just add all the letters together in the text line easier.
this is how you'd fix it @acoustic belfry
but i mean, speficitly
the moves array won't necessarily make it simpler though
actually i think you missed what i'm referring to
a list is similar to an array, just used differently
i was quite specific there
The scramble will always be 20 moves long. I read online that lists are used when the number of elements is unknown/changing and arrays are used when the number of elements is fixed. Shouldn't I use arrays then?
lists aren't restricted to when the number of elements is unknown
I'm not sure how it would make things easier though
if you treat the "amount of moves already generated" as the number of elements changing, you now no longer need to keep track of how many moves have been generated
if you used an array, you would have to keep track separately (or more realisitcally you could use a for loop)
with a list the flow becomes more flexible since the loop would no longer be bound to the amount of elements stored
hmm ok I'll look into it
here's 2 possible ways you could do it with an array:
moves = array[20]
generated = 0
while generated < 20:
nextmove = randommove()
if generated == 0 or nextmove != array[generated - 1]
array[generated] = nextmove
generated += 1
``````py
moves = array[20]
for i in 0..19
do
nextmove = randommove()
while i != 0 and nextmove == array[i - 1]
moves[i] = nextmove
```how you could do it with a list:
```py
moves = list
while moves.length < 20
nextmove = randommove()
if moves.length == 0 or nextmove != moves.last
moves.add(nextmove)
with the array approach, you have to manage moving through the array yourself - which isn't bad in itself, but IMO using a list gives a much clearer flow for logic
I'll try it thanks
like this, right?
float directionX = Mathf.Sign(direction.x);
mortemRb.linearVelocity = new Vector2(directionX * runSpeed, mortemRb.linearVelocity .y);```
yeah
nice
thanks ✨
for those who have problems with firebase in the future like me, the problem was that I had to download the google.services.json again and import it because something had changed, I don't know why, but now it works.
I tried recreating the lists example you gave me but I can't figure out what goes where. Does all of this go in the GenerateNewScramble() method I made? What references do I need at the top?
sorry for asking a lot...
But, if the script A has an int, and i want to have the same int in script B but with another value, what i should do?
how i can override that value?
Does all of this go in the GenerateNewScramble() method I made?
sure, that'd work
What references do I need at the top?
do you mean the class members here, or what exactly?
(at the top of the class, or where?)
not sure what you're asking. does B extend A?
I assume I need to make a reference to the moves list at the top of the class?
if by "top of the class" you mean as a class member, then yes
my bad,
B is an inherited of A
and the nextmove and randommove() things. What are those exactly? Sorry this is all so confusing to me
the thing is now i want to make a huge base for all my enemies, for make scripting my enemies more easier, or so i think
but before the rainbow i need the storm, to wich is where im right now, traslading my main enemy into the base
thats why im asking so much stuff
those are just placeholders, im only showing the general flow there, not full code
nextmove is a variable for storing the generated next move before commiting it into the moves list
randommove() is a method to get a random move
oh I thought you were referencing something else my bad
is the int you're mentioning an inspector field, or what exactly? what are you trying to achieve?
yes an inspector field
just make that the base script float "speed" is zero, meanwhile in each enemy differs
https://hastebin.com/share/inubusetuy.csharp
could anyone tell me why the gravity aint workin?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
why is gravity multiplied by speed?
anyways gravity is an acceleration, not a velocity
so it shouldnt be a vector3?
im using a char controller
that's not what i said, no
think about what each value you're using actually represents
x and z are magnitudes, then you multiply those by directions, then you add that with an acceleration
then you multiply that by speed, and then the time factor
move * speed is a velocity - a speed with a direction
that's what acceleration should be applied to
thanks for trying to guide me in a direction instead of giving me the script
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
aren't you supposed to call Move exactly once per frame with a cc
if that expectation is broken then it's not gonna be reliable
are you doing it all from scratch?
you should probably find a tutorial or something
are you following a tutorial?
and Move is called twice in the tutorial?
well docs don't say anything about it so 
lolol
Around here we call that "The Brackeys Error" because it's been a goddamn albatross about our necks for a decade now
Don't call Move twice per update
chat, why cant i access a var from the mauz[,]
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
What is mauz an array of
this is a very bad mindset to have
ch.Move(move * speed * Time.deltaTime);
ch.Move(velocity * Time.deltaTime);
how do i put those two together tho?
Math
gameobjects
Which property of GameObject are you trying to get
wait my bad, i am just too tired after eating an entire plate of spaghitti
i am using the array not the assigned script
you could probably have mauz be an array of ag if that's the main component you want to actually use
i figured out the mistake lol
should probably name stuff better though
they are arab words lol
"agagag" is a word?
Even then, agagagag is not a good name for a variable of type ag
yeah the "agagag" is the main one i was referring to
Yeah, mauz seems normal
though, types should generally be in PascalCase, so ag should be Ag
move * speed is the horizontal movement, velocity is the vertical movement, you can just add them together
make sure to add parentheses so the * Time.deltaTime happens last
ch.Move((move * speed + velocity) * Time.deltaTime);
yep gotit
alternatively, you could have speed multipled into move and then add velocity directly, or since it's only the gravity velocity, you could have that just be a float and add that multiplied by Vector3.down etcetc.. there's a lot of was to achieve this
its my first time experimenting w char controller bc i use rb usually, i think i like the customizability more in char controller
and the fact that it has built in slope functionality
how do you put the little square around the code
grave marks surrounding the code for inline code, 3 for a codeblock with an optional language
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
Not quotation marks.
oh
` is not '
that embed is technically wrong, 3 backticks is a codeblock
inline code is single backticks
I tried implementing some stuff but it's not letting me use that last part of the if statement 🤔
public void GenerateNewScramble()
{
while (moves.Count < 20)
{
nextMove = possibleMoves[Random.Range(0, possibleMoves.Length)];
if (moves.Count == 0 || nextMove != moves.Last)
{
}
}
}
VS puts squiggly red lines under nextMove != moves.Last
And what does the error say
it says "Operator '!=' cannot be applied to operands of type 'string' and 'method group'"
Because you can't compare a string to a function.
You probably want to run the function
https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.last?view=net-9.0
Last is a function, not a variable
I need to take a break man this is confusing
anybody have any idea why this would be crashing roughly 25% of the time? my only idea is that raycasts might be really intensive computationally when you're doing them a couple hundred times at once, but I'm not sure on that.
What is this supposed to be doing?
Why are you taking one thing, casting it to itself, then making a list of one element to loop over?
Also this. Just use gameObject. You don't need this variable at all
a chunk of the map has a bunch of children under it where other map chunks can spawn, and I want a chunk to spawn at each one
neat, thanks
That's not what this does
it works though??
This literally just stores transform into a variable named spawn
it spawns a chunk at each one
Oh god damn it this is because of transform's weird gimmicky IEnumerable implementation isn't it
Okay, yeah, so Cast<Transform> on a transform magically turns it into a collection because of a terrible design decision Unity made 20 years ago.
You can still cut all the linq out and do foreach(Transform spawn in transform)
oh yeah, that would be way nicer lol
I code like a cro-magnon
Do any of the objects you are spawning themselves have this script on it
also how could I get rid of LastSpawned? I'm just setting it to the first chunk, then later it's updated to the last chunk spawned
naw
That was when I had thought the foreach loop would just contain one element in it. Since that chunk is running multiple times, it's actually useful, so you can just do Transform lastSpawned = transform
And then change it as you spawn things
hella, ty
As to why it crashes, it looks like it's because you only actually increment i if the raycast hits anything
If it doesn't, you spawn a bunch of things and then run the loop again without changing i
So if those things spawn in within view of the raycast, you'll go infinite
Actually, scratch that, reverse it. That's a !
yup was boutta say
So if they spawn in and they are in view of the raycast, they'll go infinite
@naive pawn do you think this looks ok? How can I display the moves with text? I could only think of scramble.text = moves but for some reason I get an error. Here is the whole code.
public class NewScramble : MonoBehaviour
{
public TextMeshProUGUI scramble;
private List<string> moves;
private string[] possibleMoves = {"R", "L", "U", "D", "F", "B"};
private string nextMove;
void Start()
{
GenerateNewScramble();
}
public void GenerateNewScramble()
{
moves.Clear();
while (moves.Count < 20)
{
nextMove = possibleMoves[Random.Range(0, possibleMoves.Length)];
if (moves.Count == 0 || nextMove != moves.Last())
{
moves.Add(nextMove);
}
}
}
}
scramble.text = moves; gives the error "Cannot implicitly convert type 'System.Collections.Generic.List<string>' to 'string'" which to me seems like it should be the same thing but I guess not
a List<string> is not a string. it is a list of them. you need to specify which string you want
ah makes sense. I also tried moves.All but that gave an error too
A deck of cards is not a card.
Am entire box of pop tarts is not "a pop tart" you shouldn't have that for breakfast
I get the point now lol
Got any tips for what I can do?
Which one did you want to set scramble.text to?
The string list called moves
You can't set a string to a list of strings.
Did you want to combine the list into a single string? Did you want to set it to one element in that list?
I want to combine all of them and display that sequence on the text
Hii, should i see users connected in Analytics dashboard with just sendind logs or i need to add anything?
FirebaseAnalytics.SetAnalyticsCollectionEnabled(true);
FirebaseAnalytics.LogEvent("user_registration_success");
FirebaseAnalytics.LogEvent("user_login_success");
If you have something to showcase, make a #1180170818983051344
I've been looking at this website for a while now but I can't seem to figure out which variables go where in the argument for String.Join. Could you maybe elaborate on it? Sorry.
I must be slow or something
First parameter is the thing you want in between each element of the list. Second parameter is the list you want to join into a string
ah thank you very much
scroll down to the examples if you need. the first one shows you an example with a list of ints
So I got it all worked out but when I press play in Unity it gives the error "Object reference not set to an instance of an object" for all the lines having to do with the moves list. I have it referenced in the top of the class but it must have something to do with the fact that the list is empty at the start? I'm not sure. Any pointers on what's wrong here?
public class NewScramble : MonoBehaviour
{
public TextMeshProUGUI scramble;
private List<string> moves;
private string[] possibleMoves = {"R", "L", "U", "D", "F", "B"};
private string nextMove;
void Start()
{
GenerateNewScramble();
}
public void GenerateNewScramble()
{
moves.Clear();
while (moves.Count < 20)
{
nextMove = possibleMoves[Random.Range(0, possibleMoves.Length)];
if (moves.Count == 0 || nextMove != moves.Last())
{
moves.Add(nextMove);
}
}
scramble.text = string.Join(" ", moves);
}
}
Where do you assign a value to moves
it's empty until the GenerateNewScramble() method is called in the start function when moves are randomly selected from the possibleMoves array and added to the moves list
Where are you creating an empty list?
I assumed that's what the reference at the top of the class does?
No, that creates a variable. Where do you assign a value to that variable?
nowhere I suppose
how do I assign a value to it?
With =
Hey everyone. I'm working on a 2D arcade beatem up game in unity and I'm having trouble with the enemy AI flipping 90 degrees in the X-axis whenever I hit play. Here's a video of it happening
I have the z-rotation constrained in the inspector and here's the code I have for the enemy rn
using UnityEngine;
using UnityEngine.AI;
public class Enemy1 : MonoBehaviour
{
private NavMeshAgent agent;
private Transform player;
//public float walkSpeed = 3f;
Rigidbody2D rb;
private void Awake()
{
rb = GetComponent<Rigidbody2D>();
agent = GetComponent<NavMeshAgent>();
player = GameObject.FindGameObjectWithTag("Player").transform;
}
private void FixedUpdate()
{
agent.updateRotation = false;
// Move towards the player using the NavMeshAgent
if (agent != null && player != null)
{
agent.SetDestination(player.position);
}
//rb.linearVelocity = new Vector2(walkSpeed * Vector2.right.x, rb.linearVelocity.y);
}
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
where is rotation code or is it just rigidbody ?
oh its the navmesh agent
@rich adder I'm using a navmesh agent and rigidbody component
are you using a custom 2D navmesh ?
Yeah it's a polyshape that I put the navmesh surface component on
I have a issue, I'm actually trying to make an enemy spawner, followed a tutorial about it.
Full code is here, I gave it bird prefab but looks like its not working is anyone has solution for it?
Test your C# code online with .NET Fiddle code editor.
seems weird to me because 2d collider and rigidbody 2d are locked on the same axis so its probably breaking it when the navmesh agent moves towards point, try removing them
I put it into main camera different positions
define " its not working "
briefly yeah
showing which part of tutorial you're at wouldn't hurt either
I can send the video gimme a sec
In this Unity tutorial we're going to look at how to create enemy spawn points.
These spawn points will periodically create new enemies, giving us an unlimited horde of zombies to fight.
This is the twelfth video in our series showing how to make a full top down 2D shooter game in Unity.
The playlist for this series can be found here
► http...
@rich adderturning off the mesh collider doesnt do anything and turning off the nav mesh agent breaks the enemy movement entirely
mesh collider ?
I meant the capsule collider
its not letting me remove the rigidbody for some reason but removing the 2d capsule collider just stops the enemy from being able to move the player
did you right click the rigidbody 2d component and remove? are you getting an error wdym not letting you?
Sorry I was able to remove the rigidbody but that didnt do anything/change the rotation
I can send a video
yea its weird..can you screenshot the view so can see which way the navmesh surface from another view see where exactly that agent is going
There is a bit of an offset
thats why its not working... I thought you had more of a ZX plane going instead ur still using 2D renderer and YX ?
the orthographic view in scene view messed me up
you could deal with the navmesh walking like this but keep the sprite facing the camera , you can rotate the graphics on child only but you still need a way to interact with the collider..
You could try this instead and keep things "flat" https://github.com/h8man/NavMeshPlus
How do I code like snapping objects using empty child? Like robot arm has an empty child place next to a body and snaps when close. Something like transform and distance or something?
I'm not sure of the exact terms to describe what I'm looking for here so bear with me: Is there any way to give a script a list in the editor that I can fill by dragging in scripts with subclasses of a certain class? So that, in the main script, I can instantiate those subclasses for my game
more concrete context:
what is the Player type? is it a plain c# class or does it inherit monobehaviour? if it is the latter then it should JustWork™️ and you can drag prefabs that have a component that derives from Player into it. otherwise you wouldn't be "dragging in scripts", at best you could write a property drawer (or use an asset that does so) combined with SerializeReference to allow a dropdown list for the derived types, but it would be instances of that object stored in the array, not just a list of subclasses
it's just a c# class unfortunately
I'm not sure exactly how to implement this. Is it like a plugin/package? Also I didn't realize I was doing the orientation incorrectly. Do you think it would be better if I tried to change the whole project to be on the YZ plane instead of XY? Also is there a simple way to do that>
you missunderstood, you are using the XY plane as its default by Unity 2D . I thought you were using XZ which is more common in 3D plane as the "floor"
and yes the 2D navmesh is an extention from unitys built in navmesh but works better for 2D, its a separate addon You can read the instructions its easy to implement
whats the usecase you're going for exactly ? snap can be done different ways
i want it to snap on the face of a cube with another face of the cube. Like a socket kind of snap. Not in VR tho
Someone thought me a little but cant seem to remember the steps, something having to do with the parent having the script and the child as its position to snap
I suppose you could use that with distance but might need to roll out something a bit more complex with rays / casts
they use some kind of threshold too if im not mistaken
thats always a given, you'd need to know when can you start snapping
tbh this a bit complex todo cause unity move .position from the origin point, you'd need to know the offsets and do quite a bit of math
the idea is that I subclass Player to define the different behaviors a player could have (e.g. local player, online player, AI player) so that I can swap them out easily. The reason I'm trying to expose this array in the editor is so that I can list the possible player types that are available. Which option do you recommend in that case?
read the two options I provided and choose which of the two best suits your needs
Why is it that this triangle disappears during runtime when I change a value such as the vertex pos?
https://paste.mod.gg/kmqzrfumwxsh/0
I'm doing a basic rendermesh but it disappears whenever I change something, I have to stop and restart the player
What did you change and how
Also your code is creating new arrays every frame instead of reusing one, which is pretty inefficient.
yep I fixed it
I'm trying to make a script that takes the location of your mouse cursor and moves a sprite over to that position. However the final result is way too large of a number and I need help with calculating it down so that it works within the game canvas.
You're moving a rigidbody 2d, so guessing you want world and not canvas position
I suppose? When referring to "Get Mouse Position" is that calculated based on the world space or canvas space?
#763499475641172029
but it's probably in screen space
Sorry about that! I didn't realize there was a server just for visual scripting. Thank you!
i have this in my scriptable object:
[SerializeField]
GameObject _prefab;
I select my prefab from the list and it assigns but says "Type mismatch". Feel like i might be doing something dumb but i can't figure it out at this hour...
what does the error even mean in this context
are you assigning a field on a prefab? because you are selecting a scene object which prefabs cannot reference
what do you mean by assign a field on to a prefab ?
i mean is the object you are editing that is in the inspector a prefab
oh, its a field in a scriptable object not a gameobject
i do not mean the object being selected in the window because that is not a prefab, it is an instance of a prefab.
then it is an asset which cannot reference scene objects. you need to give it the actual prefab, not the instance in your scene
oh i thought the blue cube symbol meant it was the prefab version
you're selecting an object in the Scene tab which means you are selecting a scene object. the blue symbol just indicates that it is an instance of a prefab
I chose a different option, which is to just create the list in the setup script :P
but thanks for the help
that's so much worse
worse than if Player were a MonoBehavior but if it works it works
Why is it every time i spawn a prefab om my bullet it says the size is negative
Is the size negative
Sorry if thisis a stupid question, but what do voids do? Didn't find anything about it on the unity beginner scripting course so far
i looked it up and it says it stops things from returning a value, but if things dont return a value then how does code work in a void
so im supposeed to put void on non functions?
For the record, they're not called "voids" , they're called functions.
wait i was supposed to be learning c++?
No
when you use a printer it might be
Paper PrintPaper(Paper blankPage)
//stuff to fill paper
return (filledPaper)
but when you say, email someone, you don't get anything back from that action, hence void
no like im literally talking about the void, like in this
im not calling functions voids
Yes, you're talking about the Start function , which returns nothing (void)
void AddNumber (int a, int b)
int AddNumber (int a, int b)
Both of these are functions.
The first will not send anything back from the function, hence void (ie, "nothing"). The second will send back an int via a return line.
should i keep watching the tutorials cause idk what private means in the code here
ignore it
ok
Edited for clarity, it means the same thing.
Stop spouting nonsense, you're offering nothing to this conversation.
So you put void on functions that you dont want to give code, does that mean if you put it in a earlier code block so that you can call the function in any code block connected instead of putting the function in every code block?
not give code, give value
well
the code in the function runs regardless of what it returns
yeah i guess thats what i mean
Yeah thats what i meant, it runs but it doesn't actually do anything
These have no relation to each other. You can call the function whenever you want, regardless of where it is in your code (physically speaking) or whether it returns something or not.
So how do i know when to put voids?
Whether you can access those functions to call, depends on scope. Which is to say, if it's a private or public function.
if your not returning something you use void
When you don't want that function to send something back to the line that called it.
Here's an example:
// Example of a function returning something back to the line that called it
void Start()
{
int myAnswer = AddNumbers (2, 5);
print ("My answer is: " + myAnswer);
}
int AddNumbers (int a, int b)
{
int answer = a + b;
return answer;
}
// Example of a function that does not return anything and handles all the code locally within itself (scope)
void Start()
{
AddNumbers (2, 5);
}
void AddNumbers (int a, int b)
{
int answer = a + b;
print ("The answer is: " + answer);
}
(if you don't mind Osteel another example for the road)
public class Apple
{ }
public class TestClass
{
void Start()
{
Apple myApple = GetNewApple();
}
//This functions's goal is get an apple, so it needs to return a value (an apple)
Apple GetNewApple()
{
return (new Apple());
}
//This functions goal is to eat an apple, the goal doesn't neccesitate returning anything because thats not how eating works
void EatApple(Apple apple)
{
//code to eat apple
}
}
Alright im gonna go look up what return is and then come back and see if I can understand this
Okay i think i get it now
Make a simple calculator game
so void stops it from returning to the main code (like start or eat apple) and return causes the code to go back?
whats code flow
think about functions less logically and more like the things you do in life
string ReturnAString(string hello)
{
Debug.Log(hello);
}
void Start()
{
string functionValue = ReturnAString("return something here);
}
standing up out of bed, you don't get anything back from that, you just do it
probably not the best example
but you can call functions and set their return into a variable
finding your car keys, you do get something from that, the car keys, so you return carkeys so you can get that value after finding your carkeys
i'd be technical and say that you moved but ok
Alright yeah no that makes much mmore sense
if i ask you to find my glasses you would get something back from doing that, the glasses
Well no because if i found your glasses i would have to give them back to you
yes
actually that code is wrong wrote it on phone
so your function would be finding the glases, then maybe another to give them to me
but you need to get the glasses from the findglases function
so you return it
int Number()
{
return 2;
}
int functionNumber = Number();
to bring it out of the function
so would there be a void on the second function or a return on losing themm
there might be a void on giving them to me yeah
Hi
I have a question, in theory InTriggerCollision is like a kind of update that only updates when theres something inside the trigger? Or not?
just see a function as a random number machine, lets say you click on a button to activate the machine, the output will be a paper with a random number
Alright i'm honestly really suprised there wasn't a single youtube video explaining this cause this was super confusing before it was explained
its fine i understand it now
sounds good
First of all, there is no InTriggerCollision. OnTriggerCollision updates when something enters the trigger. If you want to check if something is continually inside, you can use OnTriggerStay.
I really like to use a Printer as a example of functions because you put paper in it, the work gets done in the machine (function) and the result comes out of the machine (function)
Are there more unity courses than just the beginner scripting one
this is a cool example because you can then return apples that could have different colors or sizes or whatever
anything can happen in the apple machine 😄
xD
i'd say to work on something simple
you'll learn way more than any tutorial
I'll try to just continue working on what i was planning to make originally
though idk how ill get multiplayer to work i'll probably just watch a tutorial
multiplayer?
i wouldn't do multiplayer
youre crazy cat boi
its just so i could play it with my friends
i wouldnt recommend it as your first expierence
its not gonna be any insane stuff infact i'll probably just use lan
even then i would recommend doing a little solo thing first
Well i'm mostly planning to make multiplayer games only in the first place so while i probably wont make multiplayer immediately it will probably be added anyways
just saying because single player games are already crazy enough
I'll try
its okay if your goal is multiplayer games
but i'd learn unity at least intermediate level first
I dont even think i've learnt unity at a beginner level 👍
Would this just be having a super basic game
sounds, game juice and one or two features
not super basic but like
i promise you'll be way more confident tackling multiplayer after
I think the fact i want to do multiplayer first makes me confident enough but i definitely lack the skill
so you know my first game was multiplayer
well now i do
gave up when i realized i couldnt sync things dropping on the floor
but if you wanna give it a try
Its fine if stuff is a little delayed, my original idea was rblx but i do not wanna do that after i saw how absolutely abysmal the delay is there
do you know stuff like client side and server side concerns?
yeah
TCP or UDP protocols?
dunno what those are
if they're security stuff i dont need to worry i atleast hope none of mmy friends would try to hack eachother
its not
if its just between your friends security isnt a problem
just use peer to peer connection or sth
They wanna do lan stuff it’s fine
Now that i think about this, this is a HORRIBLE idea, my internet is complete shit
it'll probably work anyways
it should still work
but yeah i'll listen to your idea though, i'm going to make a basic singleplayer game first
and if you wanna in the future you can add a co op feature to that basic singleplayer
brotato did that
Alright im gonna write this down so i dont forget cause its 8 am and i started trying to learn how to code like 9-10 hours ago so i am really sleeping
i am really sleepy*
public class EagleDetector : MonoBehaviour
{
[SerializeField] private EagleScript _eagleScript; // Reference to the eagle script to notify
private void OnTriggerEnter(Collider other)
{
Debug.Log(other.name);
if (other.CompareTag(_eagleScript.playerTag))
{
Debug.Log("Player in range");
_eagleScript.OnPlayerDetected(other.gameObject);
}
}
private void OnTriggerExit(Collider other)
{
if (other.CompareTag(_eagleScript.playerTag))
{
Debug.Log("Player out of range");
_eagleScript.OnPlayerLost(other.gameObject);
}
}
}
I don't understand how does OnTriggerEnter() only detects collider of a charactercontroller and not other types of colliders as well?
In the cases where the function doesn't run, do either of the objects involved have a Rigidbody
both have charactercontroller, does it need either charactercontroller or a rigidbody to be detected by a collider?
You asked about a case when there isn't a CC. What components do the objects have when it doesn't work?
in order for a collider to "see" that an object has collided with it, that other object needs to be a rigidbody
OOOOH so that's why
Hi, how i can put an animation clip inside a function wich is referenced? i mean the thing inside the ()
wait, can an object have both rigidbody and charactercontroller at the same time??
is there a way of seeing the boxcast box visually? For some reason my Boxcast isn't returning anything: if (Physics.BoxCast( center: castCenter, halfExtents: vector3HalfExtents, direction: slashDirection, hitInfo: out _meleeHitRegister, orientation: Quaternion.identity, maxDistance: 1.25f, layerMask: attackLayer )) { Debug.Log("Hit confirmed"); if (_meleeHitRegister.transform.TryGetComponent<StandardEnemy>(out StandardEnemy T)) { T.TakeDamage(attackDamage); Debug.Log("Enemy hit confirmed"); } }
context: ``` var updirection = motor.CharacterUp;
var slashDirection = castCenter - cameraTarget.position;
var slashDirectionQuaternion = Quaternion.LookRotation(slashDirection, updirection);
You could draw each of the edges with Debug.DrawLine() or you could use a BoxCollider for your casting by calling boxCollider.Cast();
would just using a boxCollider better in this instance?
probably, ye
I've check the sizes before, and they seem to be good
only problem that I have is I don't know how to check collision layers
I want to exlcude all except one
are you not checking it via attackLayer?
LayerMask is somewhat tricky to set up, are you getting any hits if you remove it?
hello, i have very basic question. When the variable with Quaternion data type is defined, what is its default value after definition? null?
wait lemme try this
do I just set the collision object in attackLayer?
What do you mean by that
thats how layers work yeah
ah ok
for most things in Unity that layer is used for both rendering and physics which is a little stupid and dumb and nowadays some things seperate it but
thats the goto
(
meleeHitCollider,
position: castCenter,
rotation: slashDirectionQuaternion,
parent: root
);```So I've instantiated a box collider, how do I ask it to return hit data?
I've read the OnCollisionEnter API and didn't even understand a speck of it
you should just have it as a reference and attach it to your gameObject instead of Instantiating it, then before casting make sure the position and rotation is set correctly and use boxCollider.Cast() for getting the data.
Unity 6 has rendering layers too
Layers is the "normal" layers that have been in forever, just too large to fit expanded
yee i know nowadays they are trying to split it up
appologies, I totally missed the end of your msg
that would be fine if not for cases like this
I have multiple melee hits that are detached from the player
I can't parent a hitbox and call it a day
can you add the boxCollider to the projectile / melee hit itself?
the projectile is also an instance, so no(?)
(
vfx_slash,
position: castCenter,
rotation: slashDirectionQuaternion,
);
Destroy(slashvfxinstance.gameObject, 1);```
At least, I'm not aware of any method that will work
What do you mean you can just add a collider to your prefab
I have no idea how to do that lmfao
Is vfx_slash a gameObject? You should be able to add it to it, or even better make a new class called "Projectile" or something that holds both a reference to the VisualEffect and the collider.
after all, it should be the slash itself that handles the hit detection, not the player.
Just use the add component menu. Then you will also need a script on the gameObject that handles collisions
it's a prefab of a Visual Effect
If you do not know how to do this stuff I suggest you !learn
so you can add colliders to that
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
there literally is an AddComponent method
but also, you have a prefab that you're cloning. you can just add it there
Something like this?``` BoxCollider meleeHitColliderInstance = Instantiate
(
meleeHitCollider,
position: castCenter,
rotation: slashDirectionQuaternion,
parent: root
);
VisualEffect slashvfxinstance = Instantiate
(
vfx_slash,
position: castCenter,
rotation: slashDirectionQuaternion,
parent: root
);```
no, not at all
you've already added the collider to the prefab, no? you're instantiating the prefab twice here
Instantiate with a component clones the entire gameobject the component is attached to
so even if I instantiate VisualEffect slashvfxinstance it has a collider?
yes
Just open up the prefab you're already using and add a collider to it
yea I did that
Then the thing you instantiate will also have a collider
does collider normally eject overlapping objects on collision?
If it's solid that's what it's supposed to do
if neither are set to trigger and they interact, yes
you can just make it a trigger though
{
[SerializeField] private int attackDamage = 1;
private void OnCollisionEnter(Collision collision)
{
Debug.Log("Slash hit!");
// register hit
if (collision.collider.TryGetComponent<StandardEnemy>(out StandardEnemy T))
{
T.TakeDamage(attackDamage);
Debug.Log("Enemy hit!");
}
Destroy(gameObject);
}
}``` had this script attached to my prefab, doesn't seem to work
The Three Commandments of OnCollisionEnter:
- Thou Shalt have a 3D Collider on each object
- Thou Shalt not tick
isTriggeron either of them - Thou Shalt have a 3D Rigidbody on at least one of them
but it has to be a trigger for it to not be pushing the player tho...
ohh
either
yeah, so use OnTriggerEnter instead
hey quick question how do i get a box like that for messages
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
use the `
Then you probably don't want to use the function that specifically requires it to not be a trigger
three before, three after your block of code
if anything large, use a code dump like !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
sorry am a idiot lmfao
using UnityEngine;
public class MovementStateManager : MonoBehaviour
{
public float movementspeed = 3f;
[HideInInspector] public Vector3 dir;
float hzInput, vInput;
CharacterController controller;
void Start()
{
controller = GetComponent<CharacterController>();
}
void Update()
{
GetDirectionAndMove();
}
void GetDirectionAndMove() {
hzInput = Input.GetAxis("Horizontal");
vInput = Input.GetAxis("Vertical");
dir = transform.forward * vInput + transform.right * hzInput;
controller.Move(dir * movementspeed * Time.deltaTime);
}
}
I know this is probably stupid but can someone tell me why this is working 😭
followed a tutorial but i have zero idea why it works because none of the movement keys that are moving the character are even in the code. I thought i would just be able to type it out and look at the code to figure it out but i really have no clue
