#💻┃code-beginner
1 messages · Page 704 of 1
Curious, why are you creating an instance of an SO (with ``Singleton.Create`)? You may as well use a C# object . . .
sorry for the confusion, my SO inventory system does not do this an does not need a singleton curerntly since they are all SOs.
can raycasts detect an item if the origin is inside that very item? for example, i place a empty transform inside a cube with a cube collider, and then point the raycast outside of the cube starting from the empty transform, would it detect the cube?
i would have to make a test case to know 100% but i am pretty sure the cast has to hit the front face of a collider
so if it originated inside a collider and cast out, i do not think that is a hit.
but to be sure i would just make a test case, would not take more then 5 mins to setup and test
In 2D there's an option for it.
In 3D no.
Is it possible to get data of an object dragged by player? I want to see if item which was dropped to inventory slot is the same as the item already placed in there. I use drag handling interfaces to drag it
you can use eventData.pointerDrag.GetComponent
Thank you
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections;
public class GameMaster : MonoBehaviour
{
// 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()
{
}
public void StartGame()
{
SceneManager.LoadScene("HammerStaff");
}
}
i am following rpg book for unity 5
!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.
and when i assign the Onclick() methord the load scene don't pop up
ngl I have literally no idea what this means
A tool for sharing your source code with the world!
did you add the scene to the build?
is show both in scene list
oh then Im not sure
Add logs in your method to make sure it's called in the first place.
nothing is appearing in the console
Then the method is not being called.
what did i forget to call in my code, becuase i have it as " SceneManager.LoadScene("Hammerstaff");"
I'm talking about the method that this call is in.
Is it possible to make an enemy that literally have like barely any at and just runs straight at you?
Sure. Anything is possible.
Because every single tutorial I’ve found has had ‘Patrolling, Attacking, Wandering, fighting’ but I literally just want it to run at me and do contact damage
That sounds like the attacking part.
Pro tip: don't expect to find tutorials that do 100% what you need. Mix and match and extrapolate knowledge from different tutorials to implement your feature.
ItemNumber itemNumber = item.GetComponent<ItemNumber>();
Debug.Log(itemNumber);
itemNumber.SetDestination(speed, nextBelt.targetlocation, this);```
so I have the above lines of code. Inside itemNumber i have the method SetDestination
``` public void SetDestination(float newspeed, Transform newtarget, Belt newcurrentBelt)
{
Debug.Log(newspeed+ " " + newtarget +" "+newcurrentBelt);
currentBelt = newcurrentBelt;
speed = newspeed;
target = newtarget;
}```
upon running the code this is what the console looks like (attached picture)
i just dont understand why everything seems to be working correctly except for the ItemNumber script
the errors claim that there is a "Object reference not set to an instance of an object" error when i call SetDestination, but it identifies itemNumber when i use debug.log
im 90% sure it doesnt cause when you log a null GameObject (such as item.name) it returns as (object)
where it should log the name of the object which im also 90% sure you didn't name object
oh wait nvm, i cant read 😭
can you provide more code?
Kinda what I normally do, I've learned so much and was confident enough to make my own custom weapon system from scratch by just watching tutorials for a couple of days and picking up on what does what
hey I have a script that requires me to assign a tilemap in the inspector but for some reason it's not accepting the tilemap that I have
I even tried making a new tilemap and it wouldn't assign
Maybe itemNumber isn't null but rather nextBelt was?
Assuming the error is on that line - error wasn't presented yet.
Maybe show what you've tried (script and image capture of inspector-field etc)
using UnityEngine.Tilemaps;
public class RoomLock : MonoBehaviour
{
public Tilemap wallTilemap;
public Tile lockTile;
public Vector3Int[] exitPositions;
private bool isLocked = false;
private void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player") && !isLocked)
{
LockRoom();
}
}
void LockRoom()
{
foreach (var pos in exitPositions)
{
wallTilemap.SetTile(pos, lockTile);
}
isLocked = true;
}
public void UnlockRoom()
{
foreach (var pos in exitPositions)
{
wallTilemap.SetTile(pos, null);
}
}
}
and I'm trying to connect this puppy to it
That is a default asset reference, it can't load anything that exists in the scene, it needs to be an asset.
You probably don't even need to assign a default just assign it on the instance you're actually using
What line is the error on
I'm not sure how to make a tilemap in the asset window, it doesn't seem like I can create one and if I make it a prefab it still doesn't work
You probably wouldn't. Again, there's no reason to set a default for this script, just set it on the instance you're actually using
much appreciated it's working now 🫡
This is my player and the camera is connected to the player so it follows it. But when the player rotates the camera follows and its really wonky, how do i fix this
this is what i mean btw
You'll need to make your own camera follow logic; Don't make the Player Camera a child object of the player as it will rotate with the player.
i think i know how to
ill try my idea and ill see what goes wrong
Would i say smth like
Transform.Position (PlayerPositionX - 30, PlayerPositionY + 30, PlayerpositionZ)
thats very crappy but smth like that
Yep thats the general idea
2nd day and im making big moves
🎊
but would i need to make the transform of the player to public
You'll need a reference to the player's transform, yes. Whether you make it public is up to you, there's a few ways to do it.
Assuming you have a CameraController script attached to Player Camera, you can have a public Transform variable that will act as your camera's target. You can then set the camera's position to the targets position minus a number, like what you talked about earlier
Yep
easy peasy
"Hello, I’m trying to use the Endless Runner - Sample Game in Unity 6, but I’m getting the following warning. Does anyone know how to fix this issue?"
There can be only one active Event System.
UnityEngine.EventSystems.EventSystem:OnEnable () (at ./Library/PackageCache/com.unity.ugui@57cef44123c7/Runtime/UGUI/EventSystem/EventSystem.cs:462)
There are 2 event systems in the scene. Please ensure there is always exactly one event system in the scene
UnityEngine.EventSystems.EventSystem:Update () (at ./Library/PackageCache/com.unity.ugui@57cef44123c7/Runtime/UGUI/EventSystem/EventSystem.cs:557)
There can only be one active EventSystem in the scene.
Run your game, go to the list of gameobjects and type EventSystem. You'll have more than one gameObject with an EventSystem.
You'll want to remove the EventSystem from one of them
Can someone help me try to fix a bug in my code
A tool for sharing your source code with the world!
A tool for sharing your source code with the world!
When caught fish is true, and the colliders are hitting, then it should trigger the sell fish thing
And the money should go up and the fish should be destroyed
But the money isnt going up
and the fish isnt being destroyed
Is "sold fish" logged?
wdym logged?
Does it appear in the console
Sold fish isnt a variable
I just make the money counter go up and the fish is destroyed
Talking about Debug.Log("sold fish");
Oh let me check
nope
one of the colliders has to be a trigger right?
I have one sphere collider and one box collider
Yes. I would make sure the trigger is working by adding a log at the beginning of MerchantAndUpgrades OnTriggerStay. I would also print something about the other collider to see what sort of things are triggering it.
ok
even when i just try to see if the two are colliding
It doenst print anything to log
why does the shop have a sphere collider
It's probably a gizmo for something else.
done. thanks
Hi, I am saving and loading time using PlayerPrefs, and getting time difference between current time and saved time but it can be tweked with changing the divice time and date, so is there any way which prevent users to do such things?
no
You can easily tell if a user skips back in time, but not forward. This is a classic game design challenge, the only real option is to use network time, or talk to a server you control, which makes it harder to spoof the time, but it's still not a 100% fix. Generally games will let a player do what they want, and mess with the time.
you would need to get the time from a server to achieve this. this also does come at the cost of your game always requiring internet connection which could negatively affect your players
oh mb i didn't process that Thom said the same thing essentially
@eternal needle Okay so there are no other options available without internet connections
nope, the user will be able to modify their own local time pretty easily. if its an offline game then tbh it doesnt matter, as Thom said, a lot of games will just let you cheat
can anyone know how I assign material via code it it's have multiple elements
I haven't looked heavily into this, just a very very quick search because I was curious. But apparently you can get the current date/time from the motherboard. While the user can still change that date/time it's far more 'work' than changing it in windows.
And I would also look into using encoded json for storing the data as opposed to playerprefs.
get materials array from mesh renderer, update array, assign array back
you must assign it back for changes to take affect
okay
was this "research" just asking AI?
It was a very quick google search that brough up a StackOverflow post. Like I said, very very quick search.
the ever-faithful school computer drained cmos battery:
relying on anything that is localy accesible is the risk, so as it was mentioned savest way is to get the time from a remote location
also, timezone changes are a thing
ugh timezones
also, leap seconds are a thing
Living in the UK actually makes this worse because I cant tell the difference from utc and my local time most of the year 😆
bwt = utc
bst = utc+1
isn't it?
GMT - UTC
BST = UTC + 1
yea non summer time is gmt/utc +-0
It's great when all your clients are in different countries. lol.
greenwich mean time kinda makes sense for the origins of it
anyway c# date time is nice so i dont usually have trouble with date and time
i'd like to imagine yall accidentally write timezone-dependant code and don't realize it until it breaks 5 months later when you suddenly aren't at Z time anymore
Idk what that means so I would 100% do this
Elsewhere in the world yea there is probably a visible difference from UTCNow and Now
2025-08-01T12:00:00Z is the same time everywhere in the world
2025-08-01T12:00:00 is not
zulu time my beloved
Hi, How do you play a video then transition into a scene ?
What have you tried so far? There should be plenty of tutorials doing both.
If I have a game object with rigidbody called rotator
inside there are children
I rotate rotator, but I want the children to hold their rotation
meaning they stay facing upwards while moving to accomodate the rotation of rotator
how to fix that?
please no crossposting
this is the right place for them to be tho
not really, they're just asking vague questions which has been crossposted
so you want them to move with the parents rotation, but always point world up?
It's probably very inefficient, but I can't think of another way. If you add a foreach child loop in your main script and set the childs local rotation in update, that should work?
Yes exactly
in a 2d topdown game
i thought of that
or in each instantiated child, updating rotation in update
but that's not really good
i want a way for it to ignore any rotation
world up or screen up
pretty sure if you're rotating on Z, everything would just rotate around and still be facing the screen
If your objects are children, they will always follow the parent rotation unless you tell it specifically otherwise. Unless there's something I don't know. lol.
make sure you're not rotating on X
how do u tell it that without saying so each frame?
im rotating on Z
it's a topdown 2d game
if you wanna change it per frame you would change it per frame
If you're rotating you parent object in FixedUpdate, it might work in there and lessen the 'calls' but tbh I'm not sure. It may Have to be in Update.
im doing fixedUpdate cuz everything is rigidBody
show us a video of the issue and your !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.
Try it, and see if it works. I really can't think of another way.
Do you child objects have rigidbodies?
how do i change background like in level 12 background changes in level 13 it changes again how to do that?
yea
so far i did this in child objects and it works, it's a bit glitchy so i think if i move it in update it will be better
but im not sure about performance xD
private void FixedUpdate()
{
transform.rotation = Quaternion.identity;
}
Okay, this could be as simple as locking the rotations in the rigidbodies
tried that not working
depends what you mean with background, in 2d you could simply replace the sprite / or material
Ah okay. Then yeah, move that line into Update. I don't think it will have a massive amount of a performance hit tbh.
And they may not need rigidbodies#
ow that works for me
Depending on what they need to do.
I need collision detection so I place rigidBodies on them
im not sure if i fix their rotation to Quaternion.identity in Update, if that affects collision detection :/
yeah this is not right if you have a rigidbody
@tiny bloom If you don't mind, could you show us what you are actually trying to do?
Right okay, yeah they won't need a rigid body each iirc. The rigidbody of the parent object should govern their collisions.
But they kind of do if they need to rotate in relation to the parent
Did anyone know how to make like the cartoon effect ?
you're going to have to be more specific, also this is the code channel
here's the script, it's attached on my player
don't worry about WeaponBase as it's just starting the coroutine
https://paste.mod.gg/dlwqkaiswlly/0
_projectile is a script of type ProjectileV2 ,and there i only have the following in Update:
private void Update()
{
transform.rotation = Quaternion.identity;
}
A tool for sharing your source code with the world!
this entire thing should probably just be part of the prefab
GameObject rotator = new GameObject("Rotator");
rotator.transform.SetParent(transform);
rotator.transform.localPosition = Vector3.zero;
var rb = rotator.AddComponent<Rigidbody2D>();
rb.bodyType = RigidbodyType2D.Kinematic;
rb.interpolation = RigidbodyInterpolation2D.Interpolate;
_rotator.SetActive(false);
Well when I import my object it's completely white (colourless), I send it from blender to my project in unity but idk why is it like that, I think it's because the colours are in emission but idk how to fix it
it's not a prefab it's an empty GO
im rotating that and adding projectiles (which is the prefab)
inside the Rotator
yes, im saying to make it a prefab
yea nvm that for now, let's make it work first lol
it was archived and merged into #1390346827005431951
how to add a animation to ui like sliding to right
You can either use a tweening library like DoTween or the unity animation system
ty
Hey guys, I'm trying to limit the rotation of a transform that is rotated on x-axis by world space and y-axis by self-space. When printing the eulerangles of the object, I'm only getting angles between 0-90 and 90-0 when exceeding 90°, while Z-Axis flips from 0 to 180. However I don't know why this happens and I can't read the actual value unity editor shows me of the object.
private void OnDivingState(ref Vector3 currentVelocity, float deltaTime)
{
Vector3 inputVector = player.RawInputVector;
float XInput = inputVector.x * _config.RotationSpeedX;
float ZInput = inputVector.z * _config.RotationSpeedY;
_transform.Rotate(0, XInput * deltaTime, 0, Space.World);
_transform.Rotate(ZInput * deltaTime, 0, 0, Space.Self);
Vector3 tempRotation = _transform.rotation.eulerAngles;
// tempRotation.x = Mathf.Clamp(tempRotation.x, 0, _config.MaxDiveAngle);
Debug.Log("Clamped Rotation X: " + tempRotation);
_transform.rotation = Quaternion.Euler(tempRotation);
}
Any idea how I can get the value from the inspector?
Referencing the transform by Transform _transform = Meshroot, while Meshroot is a public variable that's set in the inspector.
im wanting to make a 2D game where a fluid type thing fills up shapes, like an elbow curved pipe. Can anyone help me get some ideas?
Realistic fluids are expensive to calculate, how much experience do you have with unity/c#/shaders?
im not asking for a realistic fluid, a png filling up a gameobjects shape would also do great
simple and fastest way i need
I mean realistic behaviour, not styling
im a bit lost with var scene = loadscene async
there these 3 things:
yield return scene;
scene.oncomplete
scene.isdone
when the async operation is done what the called order? also which one is fired after scene is fully loaded?
behaviour wise it shouldnt behave like a fluid, just animate like fill up from 0 to 100
thats it
the simplest animation u can imagine
i am struggling to create a png fluid (fake fluid) that fills up a shape
Oh, then work with masks and https://docs.unity3d.com/2019.1/Documentation/ScriptReference/UI.Image-fillAmount.html
problem is that it works on canvas UI, and the shapes i wnna fill are in world camera gameobjects
I'm reading docs and I've found out again about ContentFile https://docs.unity3d.com/6000.3/Documentation/ScriptReference/Unity.Loading.ContentFile.html
and ContentNamespace https://docs.unity3d.com/6000.3/Documentation/ScriptReference/Unity.Content.ContentNamespace.html
there's a example usage here: https://docs.unity3d.com/6000.3/Documentation/ScriptReference/Unity.IO.Archive.ArchiveFileInterface.html
The question is, can a ContentFile be anything? Like a .txt, .json, a content archive, a .fbx, etc? What would be the correct usage?
so they are sprites?
yes
mhh if you dont have the possiblity to switch to world space canvasses I can't think of anything that doesnt involve custom shaders
got it, thanks for your input
That doesnt mean there is no solution, i just dont know any 😄
isDone is just a bool.
completed and finishing the YieldInstruction both happen after the scene is loaded.
as completed documents,
The event fires at the same point in the frame as when coroutines are executed, just after MonoBehaviour.Update methods have been run.
bet thanks
i suppose these 2 also called before the OnSceneLoaded right?
sprite masks and tile mode?
sprite masks dont work for sprites whos gameobjects i have resized
you don't need to resize them for tiled mode
can you help me with tiled mode?
i mean can u refer a doc about it or something
no clue
I was curious and did something 😄
can u brief me about this
you did all this when you can just do tiled mode lol
that's pretty cool tho
tiled mode makes it fill from center to ends
not from one end to the another
am i wrong
what pivot? this is a non-UI sprite 😄
sprites have pivots
thank you chris, tiled mode seems right. So now I just gotta have a gradient/fluid like png to which i will animate
also, like, this is the code channel
following:
- Get the current pixel position on the Y axis (Green channel) from UV (-1 to 1)
- Remap to 0 to 1
- check if current Y position is > fill
- if yes -> white alpha (full visible), if no -> 0 alpha (not visible)
- revert it and subtract from normal image alpha to retain normal alpha values
this entire convo shouldve been in #🖼️┃2d-tools
Thanks tho
I understand
i mean was a good shader exercise, wanna get better in that anyways 😄
damn yeah i should find time to do that
also i had a question, like how would this tile mode make sure that a fluid.png would properly fill up a shape of a pipe
a pipe which is curved lets say
it wouldn't. that's what the spritemask is for
Ah yes
i have an interface 'Item', should i name that interface 'IItem' or something like 'IBaseItem'?
IItem is probably better, as Base might be mistaken for a base class.
ok thanks youu
Shouldn't it OOP-wise not matter though?
What does it have to do with OOP? It's more about clear naming conventions.
Like, I don't care if a class is an interface or an ABC. I just need to know it has polymorphic compatibility and that it inherits its behaviour (whether it's implemented or not).
names should always be clear. naming something as if it is a base class when it's really just an interface is not clear
It doesnt ever "matter" what you name anything, it's just avoiding potential confusion either way
notably classes are not interfaces. they can implement them but those are separate things entirely
it DOES matter if its an interface or not
Why is this square with 50% alpha rendering above the player even tho it's behind the player on Z axis?
render layer not code question
the Z position really only matters if they are on the same sorting layer and order in layer. but yes, not a code question
Clear naming matters, because if you see "BaseItem" or something in the codebase, you expect that it's a class with it's own fields and possible method implementations, You might want to open it and implement some base features that all items share, but then you discover that it's an interface and it all blows up.
where do u ask? i only have code related channels
#💻┃unity-talk for general stuff
use id:browse to see all channels and their descriptions to find the most appropriate one for your question
im trying to implement some velocity in the end of the dash, witch works for the y axes but does not work for the x axes because of the movement script i have (im assuming), theres any way of ignoring the movement script while the other code is working?
disable the movement for the duration of that process. or switch entirely to working with forces
it does not
from a OOP perspective it only matters that the thing is above my class
what
thats like the whole idea of polymorphism
to not care what that thing is, just what behaviour it offers
interfaces perform a specific job which is why every interface you see is named IInterface
i get an error i dont understand so maybe someone smart can help me with this code it is meant to be just a simple ai that chases and attacks the player. The error is: Assets\scripts\enemy AI.cs(23,13): error CS0131: The left-hand side of an assignment must be a variable, property or indexer
📃 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
plz format your code correctly
didnt know
@ebon thistle your if statement should be:
if (distance <= detectionRange && ac == true)
= is to assign, == is to compare
people here help with issues or give advice so Id say yes
#1390346827005431951 open a thread
okay and what do you think is a good reason to prefix them with I?
thank you
the error explained it well and gave you the line number so next time try to see if you can find and fix it 🙂
This has been standard convention for a long time, it isnt just their opinion on it.
I asked for a reason. Not for statistical "evidence".
I have read many talks about this topic and the things I presented earlier have just convinced me more than something being a convention.
hi please can i have some help? i could not figure out what the error is
People already made it clear that its a naming convention and it exists for consistency. If you have issues with it, then name things whatever you want. you could name all your classes complete spam for all we care. You arent providing anything here other than attempting to appear smarter than others
System.Collections. try adding this infront of IEnumerator
You need the one from System.collections not generic
usually no need , just get rid of the Generic part of the namespace should do
unless you need things in generic namespace , sure you'd wanna be explicit but in this case they probably don't
It wouldn't be a case of one or the other anyways, you can use both namespaces
true
it worked thx, but may i ask why
Is somebody hurt? I just provided my point of view and was curious to hear if there are views that differ from mine or why there may be a good reason to include stuff like I or Base in class names.
becoz of that Generic part i imagine
But we don't have to continue it, so all good.
IEnumerator exists in both namespace, the Generic version is the one that asks for a T
oh ok that makes sense tyvm
because I prefix clearly indicates an interface
and Base usually implies a base class, this is why common conventions exists.. easily identify what you're working with aside for consistency, obviously they are suggestive and not a strict law.. You can do whatever you want..
you could also just using System.Collections;
and not have to bother with adding System.Collections infront of all IEnumerators
using System.Collections.Generic; so i just ddelete the generic part?
what difference would that make
like to other lines
think of them as folders where you find other scripts/classes
oh so generic is inside the collection
you don't need the Generic "folder" since thats the one with IEnumerator<T> you don't need
ah tysm
Nobodies hurt, when you disregard something as "statistical evidence" which makes no sense in the context, its clear you didnt understand what people above were saying while actively putting out incorrect statements.
Its not a class which you were told above. Its an interface. people have mentioned it is for naming already. That is purely the reason
It doesnt affect how the program runs in the slightest
Sometimes people will even obfuscate their program and end up with random names like C17616
Naming only matters for us developers for consistency
Since we already agreed to drop the topic I will not respond but you just mispresented what happened, but it's okay. I can understand the consistency part at least but all good 👍
Its fine if you want to drop the topic but you stating we dont have to continue is not "we" agreeing.
Anyways glad the message was understood at least
What's T i see it everywhere
Naming convention for a type parameter in generics.
generics are funn
Ahh i see (still lost 😭)
GetComponent is a good example of a generic
You can put in any component in <T>
if you're doing a save system they are clean to save multiple different POCOs without making a method for each one
Does c# understand what T is if i went and made my own type of GetComponent?
No, that's why you have to provide it when you use it
Its not that simple of a concept, to really understand how you would use generics you would need to go through a few examples.
GetComponent as nav said is a good example but you're on the side of using a generic system rather than implementing generics yourself
Your own type of component you mean?
public void GetComponent<T>() lets you use T which is provided when the user calls GetComponent<SpriteRenderer> or something
GetComponent essentially takes the type you give it, goes through the list of components and checks if that component is T
List<T> etc. all have generic
pretty powerful stuff
my script seem to be behaving differently if i recompile it mid testing
why would that be?
If you mean recompiling while in play mode, don't. Unity's version of a "hot reload" isn't really a hot reload and will just cause problems.
probably unrelated.
The reason you're not getting spammed with other warning is because you only added a whitespace and thats probably ignored, still triggered compile action.
why is compile action removing the jitter?
doubt its related, also I'm having a hard time seeing the jitter from this video..maybe my eyes are broken
the usual culprits for jittering is Camera / Roation / Movement mismatch
the speed meter
after compiling its consistent 13
looks like float imprecision somewhere, that doesnt mean the other isn't 13 (I see it often display as 12.97ish)
this is the strange behaviors you get when you compile while still running the sim
its possibly the first is running more parts of the code and causing a slight float imprecision
just a guess though
its flickering between 12.97 and 13.14
Hi o/ My brain isn't braining properly so I've once again have returned to you guys!
Right now I'M trying to create an Array of GameOJbects to populate the inside of an catalog (the gameobjects basically are the pages which i want to turn on/off, depending on the index of the current array).
I'm kind of struggling how to format that. My thought is to create a function that contains an index, depending on the which button is gettign pressed im exchanging the index with the current index. But I don't know how to write that in code, could someone point me my way?
Is it a simple for loop? foreach?
sounds like you just want to scroll through an array with index you change
Basically yeah, but how would i change the index? For loop? And how would i properly reduce the index aswell?
I plan on having a button that goes index++ and one index--
change it with a button press, assuming you're doing pagination
basically this.
you can just check the array bounds, unless you want a "warp" behavior
mhm bounds being the Length-1
eg ```cs
public void NextPage()
{
if (currentIndex < pages.Length - 1)
{
currentIndex++;
ShowPage(currentIndex);
}
}
```cs
public void PreviousPage()
{
if (currentIndex > 0)
{
currentIndex--;
ShowPage(currentIndex);
}
}```
mhm
usually thats the case lol

Well, it's not that I want to. But the topic got unnecessarily heated which I blame mainly on myself and I didn't want any unnecessary drama in here. I came back after a long while so I don't wanna incinerate something instantly
Regarding the discussion: my take on this was pretty much just that in my opinion and from what I took away from talks with people that are way more experienced than I am that it's more beneficial to look at type hierarchies in that exact mindset. It's a hierarchy. When I deal with an item, I only care about dealing with a returned value of type Item. I don't care how Item works. I don't care if it has implementations already. I only care about it being an Item that may or may not refer to types that override the behaviour. And people "always having named their classes like this" is not enough convincing material for me, that's all. And Java is an example of where people decided against that. I'm not saying I'm right or you are right. I'm just saying that not prefixing them convinces me more due to the reasons I provided.
hey real quick, i noticed there was kind of a gap in communication
you cited polymorphism as not caring about the interface - but that's about the runtime not caring about the specific implementation
the topic in focus was about you as a developer (and other devs, including your future self) being able to distinguish what a given type is for and how to work with it - that's what naming conventions are for
When you deal with an item you choose to care or not care about what it is
naming conventions provide information to support your decision, consistent naming conventions is just easy free built in info. do with it what you see fit
Is there a way in the editor to see which scripts use a specific tag?
uh the IDE maybe
scripts don't use tags, instances of gameobjects do
also how would you even know its a tag since they are so fragile
you can only search
.tag == "
or
.CompareTag("
do it better on yourself and start using components, tags are kinda trash
I know. Sorry for the confusion, what I meant is that I got an object that is tagged (its my player). But, the scripts are kinda all over the place so I need some way to see what can affect this player.
I wanna make a system where when my players ray cast touches the wall they can wall climb by alternating Q and E buttons to slightly increment their linear velocity Y but failing the combination would set it to 0, would a state machine be best for this
You don't really need a statemachine
but you could if you already have one
...yeah this is kinda why tags aren't used as much as tutorials might lead you to believe
definitely make a specific component for that mechanic rather than trying to rely on/reuse tags for multiple different things all at once
Yeahhh... If I ever create my own game I'll keep that in mind. Sadly I kinda joined someone else's project
nah I dont
Also got that imposter syndrome, I guess? Because I wanna help but at the same time I feel like I'm being slowed by stupid things.
if you have the specific tag name you could probably just search in project that specific tag, in .cs, .unity, .prefab files
!collab
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
You dont really need a FSM to do what you listed , might make it easier seperating regular movement to the climing mechanic
FSM helps so you also don't have a shit tone of bools , and ontop of that multiple bools can be true that cause weird behaviors
Imagine if you had a bool "isClimbing" and "isRunning" , your whole character breaks if somewhere both become true somehow
not home yet so I haven't actually implemented the system but I'd imagine the whole thing would just be a whole lot of embedded if statements
most of everything is if statements thats the building blocks of any logic. But how you approach the switchup is up to you.. You can even switch scripts/gameobject and all that, though thats cumbersome to do, you need to share for example falling velocity etc.
True
I would honestly use a sepearte script so the feature can be disabled/enabled with ease and self contained
can go something like
ray with certain distance hits the wall, maybe do additional checks like if its a climbable one
player in that climbing state, do the rest from there with keys, if you jump off and ray isn't touching anymore you are in the other movement state
very similiar to how a ladder logic would work
I thought u said I didn't need states unless that's just how u normally describe things anyways
I'm just used to states but same thing , you're either climbing or you're not
if you enable one script and disable another its the same concept ig
alr
can someone recommend me anything to start learning how to code without paying? im tired of making games with chatgpt or tutorials or stuff
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
tyy
Is it valid to call UnsafeUtility.Free on the raw pointer of a nativearray?
Hey im on the unitylearn thingy, and whenever I try and do OnTriggerEnter in visual studio, it just doesnt complete or whenever I do it exactly the same as in the shown video/text, it just doesnt recognize it and gives me errors, any way to fix that? Also doesnt complete stuff like gameObject and such.
(Deleted the stuff that didnt work before but theres some examples)
!ide
!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
• :question: Other/None
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
• :question: Other/None
hehe, beat you to it
double kill
at least they know what intellisense is, most of beginners code without it when ide not configured properly
Trial and error, figured something was up when I had it perfectly copied and it didnt wanna work
Hello everyone, I would like to program on Unity to be able to make small games; Do you have a course or videos to recommend for beginners ?
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
That is a sensible counter-argument, thank you very much 
That makes sense as well, arigatou.
@rich adder implemented the system but im not rly happy with how the if statements are laid out
A tool for sharing your source code with the world!
feels like im complicating things
by writing more than i actually need to
I happen to have an issue with scene loading and awake/start order: scene A loads additively (sceneLoaded event fires), then awake and start for scene A fires. Then awake and start for scene B fires, THEN scene B loads additively (sceneLoaded event fires) ?????
I want to make sure all awakes are run before any start from any scene.
I'm using a scene group loader, that is, for each scene in the group, registering the async operation and setting its allowSceneActivation to false. then, after this loop, I wait in a while loop for all operations to reach progress of 0.9. After that, I set every allowSceneActivation to true. With my logging, I see that the allowSceneActivation activations are happening one after another, then scene A says it's loaded, fires awake AND start, then awake /start from scene B fires, then scene B says it's loaded ?
Is there any way to manage a bit better this order ?
after some more testing, looks like awakes run before the sceneLoaded event is fired, for any scene. That's fine, but I'd still want all starts to run only when ALL scenes are loaded. Is there any way to do that ? (without subscribing to sceneLoaded in all scripts or something)
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
yes much can be improved, keep iterating
the nesting is not neded , you can check the patern / use an array ,maybe even an enum can suffice / bool , like that can flipflop between the two keys
wdym by check the pattern
how do I stop this sliding motion?
public float speed = 5f;
private Rigidbody2D rb2d;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
rb2d = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
float horizontal = Input.GetAxis("Horizontal") * Time.deltaTime;
transform.Translate(horizontal * speed, 0, 0);
}
``` This is all I have
Any tutorials or guides on how to make a collaborative project in Unity/github? I merged n my project blew up n I lost 2 days of progress now
You want it to do, Q-E-Q-E-Q-E right ?
have you tried GetAxisRaw instead of GetAxis? GetAxis adds a bit of smoothing to the value
Raw makes it all 0 or all 1
let me do it right now
or E-Q-E-Q
whichever one they start with
oh my god it fixed that
wait so
getaxis doesnt give 0 and 1?
or is getaxisraw like JUST 0 and 1, and getaxis is like 0 -> 1
nope, GetAxis is smoothly going from 1 to 0
it's pretty annoying to be honest and it's better to handle this kind of smoothing by yourself. I almost never use GetAxis, only the raw version
you have a rb there make use of it and thank me later
using non physics movement doesnt take collisions in consideration
wdym
i am using it, im using the .linearvelocity property
or is there another way to use it
where exactly do you use it, cant see it in your actual code
aight
lemme try using it this time, it sbecause originally instead of transform.Translate(horizontal * speed, 0, 0); I had rb2d.linearVelocity = new Vector2(horizontal * speed, 0);
but it didnt work
it has to
It's meant to provide a similar "ramp-up" to what you'd get in an analog joystick which can be very important for things like animation blend trees.
you are probably using the new input system and this code is using the old one
why would it work without physics then
well they might have changed it too, cause they said they had it previously
yeah I figured, though sometimes I found myself pretty annoyed by it, especially when other stuff is going on with velocity
If you're fully intending the game to be played primarily through digital inputs, use Raw (or use the new input system that lets you define smoothing on a per binding basis)
are you doing if they fail pattern they fall with cooldown or something ? break down each part separate. You can easily add each key hit in a List then check the last one
they fall and yh i should add a cooldown
also i tried the code out it just completely does not work
yeah I think nesting the inputs are also part of issue..
i'd do something like this maybe
if (qKeyPressed){
if (lastKey == LR.L){
Debug.Log("Failed");
return;
}
lastKey = LR.L;
patternKeys.Add(LR.L);```
you probably dont even need the list lol
what's lr.l supposed to mean
just an enum but you can probably use Keycode if you're still using old input system
idk what enums are tbh but ive been using key codes all this time so yh
just a fancy type it stores as numbers while you have readable constant name / label to it
Keycodes are also enum
pretty common are also used for simple FSM
so I should create a last key variable which is initially just key code.none?
sure that could work
also when they fail you can set that back to none so they can begin with any of the two
start by fixing the first error
not the first one in your screenshot of the error messages, but the actual first error you see on your screen
yes, now look very carefully at the method declaration
I dont know how to fix this...
have you copied this from a tutorial or are you writing this code yourself
This part of the code Im writing myself
okay and you've surely written a method before, yes?
I dont know vocab Im sorry
you can google words you don't know
but you really should consider going through a beginner c# course to learn what things are called
Ive done methods
I coded my entire weapon system myself
I just didnt know what they were called
so look at what you've done differently with regard to this method declaration than others you have written
everything else has If statements in them
Compare the line that is underlined to any other method declaration that is working correctly. Specifically look at the end of the lines
ignore the body. i'm talking specifically about the actual declaration of the method
it was this ';'
yes
Im just dumb...
just remember to always start with the first errors, a lot of times you'll find that earlier errors actually caused the later ones
how do I lock the movement on my player script?
I need to make it where you cant move after you die
if statement
Before running whatever code would move your character, check if they should be able to move. If they shouldn't, don't move them.
Does unity have built in dot and cross products
Mathf
It's part of vector
yes
how should i go about learning c# for unity?
i understand c# to a bare minimum but not how to structure scripts from scratch based on what im trying to
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
should include some c# paths
much appreciated
hey! how can i go about making a spotlight mask type thing? kind of like how the background blacks out but characters are focused on
dunno how i got that wrong, its 11PM im tired
probably better asked in #1390346776804069396 or #💻┃unity-talk
I made my Enemy attack me by InvokeRepeating an EnemyAttack method that removes 40 from the PlayerHealth Integer every 2 seconds when you collide with the Enemy with OnCollisionEnter but currently its removing 40 every 2 seconds even when Im not collided with the enemy so how do I fix that?
you should start by showing the code in question..
{
Debug.Log("Collided with: " + collision.gameObject.name);
if (collision.gameObject.CompareTag("Player"))
{
Debug.Log("Attacking!");
EnemyAttack();
InvokeRepeating("EnemyAttack", 1f, 2f);
}
}
public void EnemyAttack()
{
Debug.Log("Hit! -40");
pc.PlayerHealth -= 40;
}```
pc. refers to PlayerCombat
which I have PlayerHealth in
So, once you enter the collision with the player, you want to start a repeating clock that ticks down every 2 seconds for the rest of time?
InvokeRepeating doesn't stop
Once you kick it off it runs as long as the object exists
I want it to deal damage every 2 seconds while Im collided with the enemy, then stop when Im not colliding with it anymore
!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.
technically .https://docs.unity3d.com/ScriptReference/MonoBehaviour.CancelInvoke.html
you can cancel ALL but not 1 specific. Coroutines are the way
so using a Coroutine would be better?
https://paste.mod.gg/dpzmoeytapas/0 this is really weird - in playmode everything is fine and there are all 6 shop objects, but in built, there are only 5 (the top one is missing). how is that possible? everything else seems to be working fine
A tool for sharing your source code with the world!
coroutine or Update could also work
Time to learn Coroutinessssssssss
What are some reason that a gameObject that has a ridgidbody and a capsule collider would slowly float into the air. But then if you change its mass to 50 it slowly goes back down to the ground.
first screenshot is from built, and second from playmode (the colour change is irrelevant)
Clipping into another rigidbody possibly as a parent or child object
bad code setting velocity every frame without excluding Y
also ive confirmed that the object just isnt there, not just offscreen by adding a scroll rect and physically checking
Neither of those there is no other Gameobject and no velocity on the Rigidbody
What's the resolution of the built version vs the scene? (Meaning aspect ratio)
Looks like your UI isn't scaling to screen size properly
never mind apparently the animation i got for a t-pose had a vary small constant movement upwards.
resolution is 1920x1080 in playmode view, and its also forced that way (fullscreen and also forced to 1080p resolution) via code
but I added a scroll rect and physically checked - there are only 5 panels
{
Debug.Log("Collided with: " + collision.gameObject.name);
if (collision.gameObject.CompareTag("Player"))
{
Debug.Log("Attacking!");
EnemyAttack();
IEnumerator MyCoroutine = StartCoroutine("EnemyAttack");
}
}
IEnumerator EnemyAttack()
{
while (true)
{
yield return new WaitForSeconds(2f);
Debug.Log("Hit! -40");
pc.PlayerHealth -= 40;
}
}```
I started it but now I dont know how to stop it and Im getting an error at StartCoroutine("EnemyAttack");
wasn't really the animation either I just had apply root motion turned on
store it in a Coroutine
Don’t know what that means 😅
its a variable type Corutine
just confirmed it with a counter
I was reading this forum that worked for the people who started it and I just did what they had?
Coroutine foo = StartCoroutine(nameof(EnemyAttack));
keep a reference so you can stop it later
you can also start a coroutine via StartCoroutine(EnemyAttack())
doesnt matter you still wanna use that to stop it later StopCoroutine (myStoredCo)
where do I put this...?
youd wanna make it a field not a local var
do you understand scope?
know what a field is ?
public class Bike
{
public Wheel wheel; //Class member / field
}
...no...
something you should probably learn before doing coding in unity lol
I guess everyone skips the c# basics now
well I dont really have time to learn vocab rn because Im doing gmtk jam :p
gmktk jam ends in 2 days..
ik
its usually recommended to learn BEFORE THE JAM
you want to make an enire game 2 days before jam ends but dont know the basics. thats going to be a struggle
I already have the entire enemy and movement system
all I need to do is make it where the enemy attacks in intervals while Im collided with it
then another enemy and one boss then its just art
OnEnter startCoroutine
OnExit stopCoroutine
so Im like 60-70% done
where do I put it...
hello
wdym where? one in each method
can i get help with sum? im super new to this
!ask 👇
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #🌱┃start-here
we told you, store the returned Coroutine from StartCoroutine() as a class member and then use that variable to stop the coroutine
google "c# class field" if you still dont get it
is this channel not meant for questions?
which method 😭
thank...
we could spell it out even more but at some point you do need to learn this to understand things better
did you read anything in the bot message?
figured it out - for some reason unity had an issue with the scriptable object (only in build, not in playmode) and forgot to tell me about it in the editor :/
had to remake the SO and now it works
where do I put the class? do I just put it next to the other methods or am I supposed to put it inside something?
what class ?
the steps were to just make a field for Coroutine and store it when you call StartCoroutine so you can Stop it on exit
methods go inside a class ```cs
using UnityEngine;
public class HelloWorld : MonoBehaviour <-- class
{
void PrintHello() <-- method
{
Debug.Log("Hello, world!");
}
}```
dont confuse em
mb. i just read it but im not 100% sure if my question is about that
how's that confusing?
trying to get them to make a class field to store a coroutine
im not trying to make them do anything..
is about waht?
any channels
no worries
https://docs.unity3d.com/6000.1/Documentation/Manual/scripting.html <-- good little source
with tons of resources linked at the bottom..
don't get confused tho
actually nvm
what about the part that said. Dont ask to ask just ask
alr
I googled the class field but I dont know where to put the class
I know how to make it just not where to put it
when i hold a key to move on ground it moves and slows down until it reaches a stop
specific to colliding with the ground btw. when its mid air it does not slow down
are you moving a rigidbody ?
its probably friction
using UnityEngine;
using System.Collections;
public class SimpleCoroutine : MonoBehaviour
{
Coroutine myRoutine; // variable to store the coroutine
void Start()
{
// when you start a coroutine you can go ahead and store/cache it
myRoutine = StartCoroutine(MyCoroutine());
}
void OnDisable()
{
// if myRoutine (the variable) is assigned
if (myRoutine != null)
{
StopCoroutine(myRoutine); // you can stop the coroutine using that variable
}
}
IEnumerator MyCoroutine()
{
while (true)
{
Debug.Log("Saying Hello every 1 seconds.");
yield return new WaitForSeconds(1f);
}
}
}
the steps are
make a field for Coroutine
assign the field a value on StartCoroutine located in OnEnter
use trhe same variable in OnExit to StopCoroutine(myRoutine)
^ basically caching the coroutine when u start it.. (this specific coroutine)
*storing a reference to the coroutine we started
yea storing the reference
otherwise you have to stop them all
true true
here's to hoping this isn't another case of the "just this thing and then I'm done"
https://learn.unity.com/tutorial/coroutines just go ahead and knock out this course 🤪
bonus write-up : https://gamedevbeginner.com/coroutines-in-unity-when-and-how-to-use-them/
i like to give the benefit of the doubt atleast once
game jams are good if you actually have the baseline to test your skill live
not learning as you go for 2 days timelimit lol
oh, 💯 and to push that skillset to its limits 🤣
heck, in 5 minutes you'll be a professional at coroutines 😈
I had to go do something sorry, where do I put the field? and I use OnCollisionEnter so I dont have OnEnter and OnExit
the field would be put in w/e class is calling the coroutine (normally)
where fields go lol
OnEnter is just example of either function
am I stupid...
when I was looking at the screenshots I thought public class was a kind of method...
well this is why the basics are important..
I knew
I knew what public class was I just forgot like a dummy
Im still getting an error
{
Debug.Log("Collided with: " + collision.gameObject.name);
if (collision.gameObject.CompareTag("Player"))
{
Debug.Log("Attacking!");
EnemyAttack();
IEnumerator MyCoroutine = StartCoroutine("EnemyAttack");
}
}
IEnumerator EnemyAttack()
{
while (true)
{
yield return new WaitForSeconds(2f);
Debug.Log("Hit! -40");
pc.PlayerHealth -= 40;
}
}```
thats a local variable
Im getting an error at StartCoroutine("EnemyAttack")
I did?
show what the error says
well yeah
huh...
https://docs.unity3d.com/ScriptReference/MonoBehaviour.StartCoroutine.html
do you see the return type.
methods always have a return type.
Coroutine attackRoutine;
void OnCollisionEnter(Collision collision)
{
attackRoutine = StartCoroutine(...);```
and ur variable should be declared outside the methods.. (u want any method from inside the class to access it, for example some other method in the same class that could Stop it) so it would be a variable at the top of the class/ not inside (a) method
I just did this
wait no Im stupid
how do I make it stop after I stop colliding?
nah ur not.. ur learning ther's a difference
I forgot to tell it to stop...
not sure how'd u go about that.. i just wanted to throw in my two cents on how to cache the coroutine reference
i dont believe there's a OnCollisionExit afaik that u could use to stop it..
but if u have the reference set up correctly its easy
StopCoroutine(coroutineReference); or attackRoutine
coroutineReference/attackRoutine being w/e u named the reference variable
for whatever reason I understood what you said more than the two people explaining it in the most basic way possible 😅
yea, and i was told to "not confuse you"
it happens lol.. anyway now that u can cache a "specific" coroutine and know how to stop it.. i think ur doing pretty well so far 🍀 ¯_(ツ)_/¯
myself, i use Triggers alot.. so like a trigger a little bigger than the thing im colliding with
soo that way i can use OnTriggerEnter and OnTriggerExit to start and stop a coroutine for example
not sure its suitable for ur use-case but i tend to have better luck with OnTriggerEnter and OnTriggerExit
if I can get this enemy working than Id say Im like 70% done
i just got here. but seems that u figure things out pretty quickly.. you'll be finished in no time 🧡
yay it works... mostly
I figure things out quickly when I know the vocab... which I didnt this time
like I was able to make my entire custom weapon system after just watching a few tutorials that partially had Raycast a little bit in them
wdym? that message does exist
I learn pretty quickly and easily when I know the vocab
he said afaik which means As far as I know
ya i realized that when Ollie pointed it out
i just dont use Collision very often to know if it did or not
I think I have my enemy workingggggggg
yup basically this
/On(Collision|Trigger)(Enter|Stay|Exit)(2D)?/
💪 ya, ill remember from now on both collision and trigger both have enter and exits
but don't forget the 2d and 3d versions have different rules entirely 
I first used OnCollisionEnter on my first ever game for a game jam and I could lock its movement by just setting RigidBody to static but its so much harder in 3d
hehe.. idk man.. i just work better in 3d spaces
you can set it to kinematic, or set the GO to static maybe?
setting it to Kinematic just completely removes all collisions and forces but to get it to freeze in place you have to use static
could constrain everything as well
rotation positioning.
1 thing i do love about game-dev.. is theres dozens of ways to do everything
so one persons rubbish may be another persons holy grail
does any1 know what this error means?
or moreso how to fix it? ive looked online but its so confusing
give Unity a quick restart?
parts of that make me think it may be just a bug.. but ive never seen it b4 so cant be certain
ahh after searching now i am also confused 😅
says abunch of stuff like: usually indicates that an AnimationPlayableOutput object, which is responsible for direting animation data to a specific target (Like an ANimator) component has not been properley initialized or assigned..
typically occuring when a PlayableGraph is created or manipulated 👀 ya, idk what any of that means.. possibly #🏃┃animation would have a better answer
legacy animations cant be in a blueprint
if it is indeed related ot animation
if it's just the legacy thing there'd be a warning iirc?
yayyyyyyy! Enemy 1/2 complete
Enemy 2 is just going to use like 5 minutes from a 20 minute tutorial
then its boss coding...
uh oh...
Following a tutorial, why some tiles block view of the character while some tiles are under the character?
#🖼️┃2d-tools not a code question
Why dont unity serialize interfaces
There is SerializeReference but only works on non UnityEbgine.Objecy
it just be like that
can someone tell me why this code is not working it's working if i remove "* forwordInput/horizontalInput"
Because it reads input only once at the start. Those lines should be moved to Update
phk
thanks
How do I rotate a gameobject into an absolute angle? I want the gameobject to point 40 degrees to the right, when my input on the x axis is positive and 40 degrees to the left, when x is negative. My current solution keeps adding the angle with each frame.
void Update() {
if (_moveInput.x > 0)
{
_animatorPulseEngine.transform.Rotate(40,0,0, Space.World);
} else if(_moveInput.x < 0)
{
_animatorPulseEngine.transform.Rotate(220,0,0, Space.World);
}
}
Rotate, well, rotates from the current rotation
you want to set the rotation, so rotation = ... or eulerAngles = ...
I am sorry, but I don't quite understand how I am supposed to set the rotation
i just gave you examples
Use Quaternion.Euler() and assign to transform.rotation
transform.rotation and transform.eulerAngles let you set the rotation
the former is a quaternion, the latter is a Vector3 of euler angles
Ah so you meant it that way. I was confused, because I assumed rotation and eulerAngles like you said were meant to be values and not methods from transform.
That doesn't make sense
Basically you should assign a new rotation to override it to what you want
Rotate() will manipulate the current rotation so won't do what you desire
Like I said, I was just confused
they are properties of a transform, not methods
My bad
I'm trying to make a character controller rn but i'm having an issue with jumping. It's inconsistent, every time I jump, the jump height is different and I don't understand why. Here's the code https://paste.ofcode.org/NVjv4ajrgNWYUWAL4X4xqf
Don't multiply velocity by deltatime
Ah damn really ? i thought i had so its consistent whataver the framerate is
what should and shouldnt be multiplied by deltatime ?
it depends on the usage
if you have a value in x per second, and you want a value in x per frame, then you use deltaTime
if you aren't in that situation, you don't
that's what deltaTime is, a conversion factor - it's seconds per frame
Ah ok, so multiplying the velocity by deltatime actually did the opposite of what I wanted right ?
you also shouldn't be using deltaTime on lookDirection if that's mouse input
I removed it too
yeah - velocity is a value in x per second, with deltaTime you were giving it a value in x per frame
with the mouse thing, mouse delta is already in x per frame
your player.Move should have a * Time.deltaTime, because velocity is being treated as per second, but Move is taking a delta position per frame
Dam alright thanks, removing deltatime just amplified every movement by 1000, i'll add some multipliers to reduce that
player.Move(velocity * Time.deltaTime);
like this ?
(although it should probably be in Update instead of Gravity to avoid confusing yourself in the future)
(and also you don't need the isGrounded check to apply gravity, you should do so regardless so the CharacterController stays in contact with the ground)
(also btw Mathf.Max exists)
I use it so the downward velocity resets on contac with the ground
yeah you probably didn't need sensitivityMultiplier lol
oh yeah, that's correct. my bad.
the right thing is to apply gravity regardless of being grounded - as in this kind of flow
if grounded
reset y velocity
apply gravity
I use clamp instead because i had an issue where if i simply set the velocity.y to zero when grounded i wouldnt be able to jump, so i made the minimum 0 and the max any positive number
yes, that's what Mathf.Max would achieve
ah ok thanks, i didnt know
you mightve been using Min before, which is an understandable mistake - it reads like "with a minimum value of x"
but it's kinda the opposite in this kind of usage, Max takes the larger number so it is applying a minimum value
on the contrary it was set to 0.1 so i dont have to put an absurdly small number in the actual sensitivity
ah
never used min either, i just used clamp cuz it seemed more intuitive to me
thanks you so much though the jumps are now consistent
So i guess i'll only apply deltatime to the actual move function instead of the values it uses
Time to make the little bean actually move
so im trying to make it so the player is only restricted to only one jump and i keep getting errors that i do not understand
and also collisionInfo isnt working for some reason
theres quite a bit wrong with this
this is running off my little understanding so this makes sense
well as we can see there are 3 ~~~ of red lets start with the first one you've incorrectly written your method / function (an example of what they should be) https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/methods
problem 2 your if statement seems off ( here is an example of what they should be ) https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/selection-statements
There will be more errors even if brackets are added to create the method scope, as you can't declare a public variable inside of a method
and finally not to spring alot on you but you can't compare tags with == you should something like https://docs.unity3d.com/6000.0/Documentation/ScriptReference/GameObject.CompareTag.html
alr lets start studying
you can
ok well than doesn't mean you should it's less efficient
not to be a nuisance but im a little confused with problem 1
it's marginally less efficient, the real reason is the warnings you get with typos, iirc
but mainly i just want to point out that == is a thing with strings.
here's what the method should look like if empty
void OnCollisionEnter(Collision collision)
{
}
you have void OnCollisionEnter(...);
the ; is indicative of a variable declaration or a statement, but you want a method here
you used the wrong symbols so c# doesn't know what you're trying to do
so no collisionInfo
just collision
that's just the name, it doesn't matter
you can call it whatever
the problem is what Chris said
so the lesson there is Methods dont have a ; to finish a line?
yeah, you don't need ; for everything
like i said above - just for field declarations and statements, and also with for
ok makes sense
any way to make it so that the sound plays when the TimerUpdate is a specific number, or is this entirely incorrect?
hover over the erroring code to see what it's trying to tell you
though, TimerUpdate can't be a specific number
wait nvm i get how to do it now
it's an Action
yeah i was intending to just mention the important part but yeah that's ambiguous to the standalone Action
how can i transfer some values from one scene to another? (without PlayerPrefs and similar things, i dont want to crap in the registry or savefile)
scenes don't hold values, components do - this question is pretty broad, what are you trying to achieve?
The most common approach is a DDOL Singleton holding the data or serving as a message bus for it.
i have a scene with my game, and it is action. So i cant just pause the game, i want to instantly switch to pre-loaded winning screen and pass all the needed params to save
but i think im simply not
https://youtube.com/shorts/9ZmpcNhyRHY?si=uOhRld8gpnpuM5aB How does one achieve this kind of wavy-like UI thingy for immersion?
What a battle
like and sub as we get closer to 700 subs!
unless it can fully be done with JUST UI game objects
in which mb
probably some sort of sprite animation or shader, and then moving it to the side
wrong channel
shader?
wait- what if I just have a very long PNG of said "wave art thingy" then just continuously move it to the left, then when it reaches the end teleport it back to its original position so it lasts forever
that could work
how can i preload 2 scenes at the same time? i had the issue of one activating after another
If you mean the top and bottom bits it looks like some noise with processing via a shader
They will always activate at different times.
i have 2 asyncoperations and thats it
Yep
They will always activate at different times
You need to rewrite your code to be able to handle that
!collab
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
<@&502884371011731486>
was spammed here too , not sure where else..#1182461825829314570 message
I thought I finally figured it out… I had it where GetComponent gets EnemyCombat… now it’s worse than before and literally NOTHING is happening
Honestly ts stopped being fun the second I started coding the enemies
you lack core understanding of what a component is and how to get instances of components from other gameobjects to interact with them
as others said, following some learning courses will help you understand this but guess no time for that rn
It would honestly be faster to just learn rn… if my computer wasn’t running the videos at 2 fps
You can learn without having so many things open, including unity..
maybe it cannot handle the unity editor and browser?
I closed out of literally everything besides the browser and it was still lagging so Im just using my iPad
And I reopened everything
Because why not
Like the first 30 minutes of this guide I already know…
‘Can you open your project in Unity Hub?’ Hm… considering I have made an entire game before… this seems pretty tough
im trying to make a grab system in unity everything is supposed to be good but i have this error
ill upload the code in js a second
js hmm
!code 👇
bot is on holidays
what
double click on the error where does it take you exactly?
and you can delete the big wall of text
it takes me to the drop object function to the Rigidbody rb = grabbedObject.GetComponent<Rigidbody>(); line of code in it
grabbedObject is null then
how do i fix it the grabbed object isnt staying in the holdpoint position when i click e tho
fix it by not accessing a null object
make it not null by assigning a value
the first if statement is really weird
wdym assign a value to it to the rb?
if Key / else
whys it weird
yeah i think you are dropping it the minute you pick it up which then sets the second if to be false
oh
cause GetKeyDown is only for one frame so the frame right after calls
else
{
DropObject();
}
i just noticed
let me see if i change it
i fixed it tysm idk how i didnt notice that
how do i send codes?
!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.
can i just copy paste it here
better use codeblock or one of the websites
use the links
the ui(dialogue panel) is not showing up
Making a game that involves placing tracks on a grid and I have UI buttons to switch between track type. Issue I am running into is that when I click a button it will place a track on the ground behind the button. The fix I am thinking of is affixing colliders to the camera in the button areas but is there a better way?
and you did the complete opposite of what was told to you
ohh
show the setup
hard to suggest anything without context
do i put all inside one all seperate them
A tool for sharing your source code with the world!
the site allows multiple files in 1 link
the dialogue ui is not showing up. i know that the conversation works fine because i used debug logs. the problem is that i dont know why the variable is not set to true so it never shows up
If you click green tile it places a track
I click the UI buttons on the top right to choose type
If a green tile is behind the button it will place a track when I attempt to switch
The white boxes are gonna have a collider so the mouse check hits them first
youd wanna check if your mouse is on UI so you dont hit the green by accident , is that right?
Correct
I would switch this to IPointer interface so you can knock the issue with ease
otherwise you can try EventSystem.current.IsPointerOverGameObject()
or
bool IsPointerOverUI(){
PointerEventData pointerData = new PointerEventData(eventSystem){
position = Input.mousePosition // Device.current.position.value -- for new input system
};
List<RaycastResult> results = new List<RaycastResult>();
raycaster.Raycast(pointerData, results);
return results.Count > 0;
}```
which both essentially doing same thing using the Event System , which is what IPointer would use anyway
and which part is that since these scripts are a mess and you didn't even bother separating them by file / tab
A tool for sharing your source code with the world!
i deleted some irrelevant codes too
You sent the homepage.. you didnt hit save before sending.
quick question, i know c# past the basics, some system IO, a bit more, where can i learn how to use C# in unity, like where to look for certain things ect
Oh crap mb
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
A tool for sharing your source code with the world!
this should work now
I did try debugging it and i know where about its gone wrong but have no idea why
so where is supposed to do the thing
Whats the thibg
show the thing you expect
For some reason, if I move while jumping, my player character stays in the air for an unreasonably long amount of time and I have no idea how to fix it
here is my code
using UnityEngine;
public class PlayerMove : MonoBehaviour
{
[Header("Movement")]
public float MoveSpeed;
public Transform Orientation;
float HorizontalInput;
float VerticalInput;
// KeyCode
public KeyCode jumpKey = KeyCode.Space;
bool Grounded;
public float JumpForce;
public float DownForce;
Vector3 MoveDirection;
Rigidbody RB;
private void Start()
{
RB = GetComponent<Rigidbody>();
RB.freezeRotation = true;
Grounded = true;
}
private void Update()
{
MyInput();
MovePlayer();
if (Grounded != true)
{
Invoke("ReverseJump", 1.0f);
}
}
// Gets Inputs
private void MyInput()
{
HorizontalInput = Input.GetAxisRaw("Horizontal");
VerticalInput = Input.GetAxisRaw("Vertical");
if (Input.GetKey(jumpKey) && Grounded == true)
{
Jump();
Grounded = false;
}
}
private void Jump()
{
RB.AddForce(0, JumpForce, 0, ForceMode.Impulse);
}
private void ReverseJump()
{
RB.AddForce(0, DownForce, 0, ForceMode.Force);
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "Ground")
{
Grounded = true;
}
}
}``` (Had to remove some stuff cuz discord)
ok
what's downforce set to
Half of jumpforce
It works well if I stand still while jumping, just not while moving
that doesn't tell me anything
It is set to -5
How do I send the code from the paste site?
A tool for sharing your source code with the world!
Player hits x, then it should trigger the conversation (in dialogue manager, talking()) then in the talking function it should set talk to true therefore triggering the code in the update function of DialogueManager if (player.talk) {dialogueBG.style = DisplayStyle.flex} , showing the ui, and set talk to false in the notTalking function(in player controller), after the dialogue is finished.
you have an RB but you're modifying transform.position, that will lead to physics system desync
if you have an RB, just don't touch transform
oh ok
so Debug.Log("should display"); is working?
so player.talk is false
this is another reason not all variables need to be public
Oh
go to the player class it usually tells you in IDE where that var is referenced
It just highlights them and its not really clear plus it doesnt show in another script
wdym it highlights them
Every jump is now a different height. And if I move while jumping the jump is twice as tall than if I stand still
Where do you see where it's referenced
In visual studio
there should be a headline on it that says "x references"
not here the variable itself
or right you can right click it and do Find All References
what's the current code?
A tool for sharing your source code with the world!
Same thing just changed the transform.position to RB.position
you shared the homepage
Oh mb
that would still probably be jittery
you probably want to use linearVelocity or AddForce instead
that way you get proper interpolation and collision detection
Thats the only url thats showing up on My screen
then you haven't hit save yet, probably
I tried to use addforce, but it wasn't working so I just went for that instead
A tool for sharing your source code with the world!
what am I lookin at
I am trying to make it so when the player touches the wall it should send a debug.log but its not working. the wall is a child of an empty gameobject that has the script while the wall only has a mesh collider and a rigidbody. did I do something wrong? https://paste.ofcode.org/EfqZjqF96eNFGTeiagbqKt
have you tried using linearVelocity?
yes
