#💻┃code-beginner
1 messages · Page 594 of 1
I can assure you there are much more efficient ways to learn "the right way" than having some man child cuss at you in a beginner coding forum. It's just weird and sorta tasteless to offer help to someone (by being here) and then act like that.
Raycast (and most other similar things inside unity) use the physics engine to query a point from A to B, and pass along information of that "hit" to, well, whatever you want. I saw you mention mouse click. Raycast and world origin is what 99% of people would say
Sure, you might not need the directional information, throw it away
but you didn't seem to grasp overlap, so I offered an alternative to get you moving fast instead of getting abuse hurled at you
Raycasts in 2D physics are on the 2D plane, and although you can pass an arbitrary vector and 0 distance to the API, it's the kind of thing you generally should avoid as it's if you have to justify something silly (a zero-length direction, or an arbitrary direction with 0 distance) when using an API you're probably using it improperly and may walk yourself into an edge case
You don't have to know the whole coding API, you just have to look at the methods of the one class you're interacting with, and find what fits best https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Physics2D.html
Yeah, that's sometimes the point, I don't even know those methods exists and I have no real way of knowing other than asking
Like would a caveman search what toothpaste is? No, cause they don't know that's a thing
if a caveman had google and tooth pain they would soon find out
"Thingy to stop teeth pain". Sure they would find something accurate
Are you the same Thomas Ingram from Effort Star?
sure
No, I joined to work on Enter the Chronosphere
Do you find that working as a tools designer is more rewarding and lucrative than a generalist or lead programmer?
I'd rather not randomly have an interview in a coding channel; but I'm currently doing generalist/lead work. I just have a tools specialty because I like them
Sorry, not my intention. I just knew about Effort Star for a bit, fanboyed for a minute, and realized you and I were in the same position. I don't tend to see meet many career gamedevs so I thought it was an interesting perspective. Did not mean to rattle you
See ya!
what does this even mean?
The first error is suggesting you're missing build tools needed to use il2cpp. Click on it, and see what the details are. That probably has tools you're missing and need to install.
it says i need these but i already have them
In visual studio do you have a c++ compiler and windows sdk installed? I think thats separate from windows build support module you install from unity hub
how do i check if i do?
https://discussions.unity.com/t/installing-visual-studio-2022-with-il2cpp-support-on-unity/899685/4
This should give you what you need
!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
Can someone tell me in a tetris like game. how do i make the blocks occupy multiple cells in the grid. currently what i have is tht the block only occupies one cell that corresponds to the centre of the block.
Make a block object that contains a list of indicies that it occupies at once
Is this link the right place to learn InputSystem ?https://docs.unity3d.com/Packages/com.unity.inputsystem@1.0/api/UnityEngine.InputSystem.PlayerInput.html
I'm working on a puzzle game and the block doesn't really occupy any cell, I know it's location (origin) and its shape and size, when moving it I check the array I use for the static blocks to see if it /would/ fit there, rather than actually fitting it in there.
Try the manual link at the top, it might give a better overview, also make sure you're on the right version for your editor.
I can't find this link
Is that the old version?
um how are you checking the size and shape of the block? I am also using static blocks
You really don't need to know about any of that. All you need to know is if the index below the blocks are empty or not (Though if the block below it is part of the same block we should consider it empty because it's actively moving)
I have a little loop that lets me iterate over the shape of the mobile bricks and check that against the static grid.
What version are you using?
i feel so dumb rn
hi i got a goofy question
whats you guys optimal way to shuffle a list or hashset with seeded unityengine.random function
this is a code channel my good man, and that is not a code question. Delete and ask in #🖼️┃2d-tools
Ah, yeah I'm not too sure of the question here. If you need help with how the blocks move throughout the grid, those are the questions that should be asked here.
Do you need/want to use the same set of random numbers? Is that what you're asking?
im doing auto generated rooms, so far the sizes, the layouts are seeded with the initstate, the rooms in general are stored in a simple hashset
trying to shuffle the rooms
Fisher–Yates shuffle. You just have to switch to using Unity's random if you want to. Seeding in this case is as simple as adding it to the constructor.
private static Random rng = new Random();
public static void Shuffle<T>(this IList<T> list)
{
int n = list.Count;
while (n > 1) {
n--;
int k = rng.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
Not sure if doing this on a hashtable is as good on performance or if you maybe want to move to a list or array first. I don't think it matters.
yea i understand this one, guess this will have to suffice
send an mp4 or use streamable to post vids . . .
I'm trying to use interfaces to define things in my game...
like for instance any interactable.. (right now im working on Points of Interest).. soo I want to start by just getting data from it when I click..
right now im getting errors i'll have to work thru.. but i wanna know am I doing this right?
just wanting to know if im assigning these correctly.. i do not think i am
nothing visible in inspector as well.. (thats what im trying to figure out right now lol).. and im a bit foggy this morning 😭
What is supposed to be seralized here
i was thinking I could asign the things lke Name Description Interaction Hint via the Inspector..
is that the problem? I need to serialize them? I thought public was good nuff lol
C# getters are just methods
you need a field
[SerializeField] private string name;
public string Name => name;```
🙏 thank you bro.. im dumb..
today may not be a good day for coding
[SerializeField] string poiName = "POI Name";
[SerializeField] string description = "A detailed description of the POI.";
[SerializeField] string interactionHint = "Click to focus on this POI.";
public string Name => poiName;
public string Description => description;
public string InteractionHint => interactionHint;```
it was that simple 🫠
im just feeling my way around interfaces.. i've used them for basic things like Interact() method.. but decided to try to make a modular system for once..
anything clickable basically
Could also do:
[field: SerializeField] public string Name { get; private set; }```
super sekret backing field serialization
and since public interface IDescriptive : IInteractable
I descriptive inherits from Interactable i probably dont even need to derive the POI from that do i?
I would just serialize the property to avoid creatinga a field as well . . .
Yep, what Mao just posted above (I missed it) . . .
like 86in this guy
public class POI : MonoBehaviour, IDescriptive, ICameraTarget
{
[field: SerializeField] public string Name { get; private set; }
[field: SerializeField] public string Description { get; private set; }
[field: SerializeField] public string InteractionHint { get; private set; }
public bool CanInteract() => true;
public void Interact()
{
Dbug.Log($"{Name} Interacted with!");
CameraController.Instance.FocusOnPOI(this);
}
public Transform GetFocusPoint() => transform;
public float GetOptimalZoom() => 30f;
}``` i do *like* that alot better..
atleast from first glance
This is what I do. And yes, you don't need to derive from IInteractable if IDescritpive inherits from it . . .
ye that's right. What's interesting too is if your interfaces diverge and somewhere meet up again, you still just have to implement that one method they both share.
CanInteract should be a property here . . .
Like, interfaces can run into the diamond problem but it's resolved differently (basically it just accumulates all implementations, but you'll never implement duplicate methods)
The same applies (using a property) to GetFocusPoint and GetOptimalZoom since you're returning the transform . . .
You can just remove the Get part of the name . . .
So I have two main problems
1 I made a script to the bullet follow the cross hair and for the bullet come out of the tip of the gun , but for some reason the bullet always comes out of the same place and doesn't follow the tip of the gun
Also I also I'm trying to assign an UI text for the ammo counter but the script I made for the weapon systems won't allow the text UI into the automatic ammo counter.
Sorry if this sounds confusing I'm new to this
for the second point: you're probably mixing up the legacy text, UnityEngine.UI.Text, with a TextMeshPro type, TMPro.TMP_Text
IMO using methods here is alright
TMP_Text can contain both TextMeshPro (for non-UI text) and TextMeshProUGUI (for UI text)
It makes it clear that some calculations happen when they are called
@timber tide @cosmic dagger thanks guys.. i think i'm on the right track again (for now) 🧡
That's why I mentioned switching to properties as there are no calculations. It only returns a value . . .
If there were calcs, then I agree that using a method would be fine . . .
It won't break or ruin anything, for sure, but mixing properties and methods when they all return a fixed value can be misleading . . .
I use properties even when there's some math going on
As long as it's not too often, I pray . . .
I can always switch to something that caches the computation later if necessary
I prefer to use methods only for things that require input or that change the state of the object
problem with properties I like to keep them in the header space, but they start feeling like methods if I start doing logic in them and then i start having identity issues for where they should be
Haha, I only place logic in the setter. I try to stick to that and only return the value in the getter . . .
!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/, https://scriptbin.xyz/
📃 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.
https://paste.mod.gg/jrvpurjqjevp/0
anyone knows why i cant rotate my camera
A tool for sharing your source code with the world!
But the logic is mainly for clamping, checking if the value is different enough (tolerance) to be considered a change, and sending out an event. I avoid having the property interact with other methods in the class to keep it encapsulated to itself . . .
a property describes a property of the object. it does whatever is necessary to compute this value
of course, a property's get accessor should have no side-effects
i've just started using them.. or atleast trying to..
bold, italicize, and asterisk "should" . . .
4 + years of hobbyist stuff and im just now comfortable enough to try to use them
they're trivial to write
especially as expression-bodied members
public float Coolness => baseCoolness + GetCoolnessBonus();
I like just sticking to methods if it's nothing something that I can inline like that
it's more descriptive too when it comes to things like resources. Like sometimes I prefer doing a HealHealth(int value) and DamageHealth(int value) instead of a general Health property
This applies to what Fen and I mentioned. It requires an input, so using a method here makes sense. The Health property would only retrieve the value while the methods change its state . . .
in that case, I would have a get accessor to retrieve the current health, as well as a set accessor that unconditionally sets health to an exact value
then I'd have methods covering other ways of changing health
Yep, exactly that . . .
Hey, im trying to create a backrooms-esque first person shooter game, where 2 people play against each other in a constantly changin backrooms map, in the sense that there is a constantly sized 100x100 square, but the walls inside constantly change when you arent looking at them. Does anyone have any good tutorials or tips on how to do the wall changing thing? it can't exactly be random as i dont ever want the players to get stuck or be unable to find the other one. I realize that this is similiar to procedural dungeon generation, but i havent found many tutorials that relate to this
Procedural generation with updates is a bit more challenging than usual!
One thing that comes to mind is to guarantee that there will be at least one connection between every, say, 10x10 grid square
so this would be a valid square, for example
you could then freely swap them out without any consideration at all for the neighboring cells
Wouldnt pathfinding work better? where the shortest distance between the two players HAS to be in some range?
You could definitely do that.
I thunk this would take away from the backrooms effect, as its mostly hallways and not just periodically spaced boxes
You just need to be able to ask "do these two cells connect?"
then you can run Djikstra's on a candidate layout and see if a path exists (and is short enough)
Regardless of being hallways or boxes, you have to connect from one to the other . . .
if you want to avoid large pre-made cells, it gets a little more complex
but the base idea should still work
You can create a variation of hallways and boxes that fit into this 100x100 space and mix them up . . .
you'd construct a graph based on whether each, say, 2x2 square is reachable from its neighbors
"Backrooms" maps tend to be decently grid-aligned anyway
Would maybe a random maze generator with pathfinding work?
thats mostly just hallways and ive seen a few good ones online
The tricky part would be updating parts of the maze during gameplay
I guess you can just reset part of the map to the "unfilled" state and then rerun the generator
as long as the generator you're using can handle that
You know what --
this would be a great place to use the "wave function collapse" method
Couldn't you just destroy all walls that arent currently being looked at, and then regenerate a maze around those not destroyed walls?
And it wouldnt be constant, but like every 2 seconds, and if this was too complex, i could just make the lights go out every 5 seconds, and just make a random map
that completely removes the complication and is just procedural generation
As long as you can restart the generator with a partially generated map, it's trivial
what things would you recommend me to look at?
the wave function collapse method?
found this : https://github.com/davidpcahill/The-Backrooms-Map-Generator, ill try to make it constant and changing in game
https://selfsame.itch.io/unitywfc
here's an example of that technique
There are several different things that get called "wave function collapse" -- this implements several techniques!
The "OvelapWFC" mode takes an example layout and learns patterns from it
"SimpledTiledWFC" requires explicit rules to be defined
I've used this for a game before. It was a little awkward to pick up
thank you so much for the help, ill look into that
I had trouble with it producing empty maps 90% of the time
I believe that was because my tile rules were too restrictive
I've also implemented the "tiled" technique on my own before (using Entities, and doing the work in a Burst-compiled Job)
super speedy
hi how to restart time in timer script? i need line of code ```cs
public float TimeLeft;
public bool TimerOn = false;
public TMP_Text TimerTxt;
void Start()
{
TimerOn = true;
}
void Update()
{
if (TimerOn)
{
if (TimeLeft > 0)
{
TimeLeft -= Time.deltaTime;
updateTimer(TimeLeft);
}
else
{
Debug.Log("Time is UP!");
TimeLeft = 0;
TimerOn = false;
}
}
}
void updateTimer(float currentTime)
{
currentTime += 1;
float minutes = Mathf.FloorToInt(currentTime / 60);
float seconds = Mathf.FloorToInt(currentTime % 60);
TimerTxt.text = string.Format("{0:00}:{1:00}", minutes, seconds);
}
}
One thing that's really cool about wave-function collapse is that you can "seed" it with some tiles, then let it fill in the gaps
So you could nuke most of the map, do a random walk to draw a single valid path between the players, and then run the generator
That seems perfect for what i need to do
I'm not sure how easy it would be to do that with the package I linked, though
The algorithm isn't actually that hard to implement
(especially for the "tiled" variant, where you don't try to learn valid patterns from an example map)
Each grid cell starts out with every possibility -- every tile in every possible rotation
When you place a tile, you update the possibilities for its neighbors
you intersect the existing possibilities with those allowed by the placed tile
so if a tile used to accept {A, B, C, D, F}, and the newly placed neighobr only allows for {B, C, E, F}, the tile can now only be {B, C, F}
you "collapse" the most-constrained tile until you run out of tiles to collapse
(you can also use probabilities instead of a binary "yes/no")
so a straight road usually has straight roads as neighbors, but sometimes has a corner
and you can leave very small chances for empty tiles to prevent impossible configurations
Hey I think something is locked in a position even after I set it to follow the camera , is there a check box I can see if something is locked or not ?
How did you set it to follow the camera?
Log the position of the object before and after, or just look at its position from the inspector . . .
Hello, I am trying to create a main menu for my game.
For some reason my buttons are not clickable.
I have done the following:
- created an event system in my scene
- My buttons are inside a canvas object, the canvas does have a raycaster
- All butons are interactable, have Raycast Target On
- The TextMeshPro component objects dont have RayCast Target On
do you have an Event System in the scene
Put the mouse over the button and look at the EventSystem, it will tell you which object it thinks the mouse is over
(new Input system only if you click on something)
i made it a child of a child of the camera , it has the same result when i try to make it a only a child of the camera
What is the result you're seeing? If it's a child of the camera, it's going to move as the camera does and remain in the same relative position
well it moves with the camera , basically i tried making a bullet system but the bullet always goes in the same direction and wont follow the gun at all
So what's the code that determines the bullets direction
expand your EventSystem window during playmode
you want me to post it here right ?
cant see shit from this ss
!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/, https://scriptbin.xyz/
📃 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.
click on something, and see what "Selected" tells you
it keeps saying "Null"
dam..new input system makes this extra annoying to debug
can you show your canvas settings ?
I hate it :)))
the old input system module would tell you what mouse was currently hovering
Yeah, it doesn't give you much info in the preview area for some reason
Time to do it manually!
someone got too lazy to implement it 😄
check out EventSystem.RaycastAll
yeah you might have to manually inspect it
raycaster is there yea, I have a feeling something is covering your raycast
You'll need a PointerEventData to invoke that
You can construct it by hand or reuse one from another event
I wonder how hard it'd be to add that extra data to the preview area
could it be the background Panel?
maybe
The Panel will be behind every other object
also true, first = last in UI
I suspect you have a very large Image or TextMeshProUGUI component that's getting in the way
Look at the size of the rectangle as you select each object
have you check the rect transforms of each text
also you can just disable the raycast on TMP under Extras
I usually do this as precaution incase my layout decides to poop on some device
Indeed. No reason to make that a raycast target
I try to proactively disable that on anything that isn't going to be clicked on.
I did that
The main menu object is very large, I wasnt sure how to size it properly
sobbing
ah yes IIRC even empty Containers can act as raycast target if child have raycast targets
not sure what you mean by "Container" here
There is nothing to hit on an empty game object
rect transform that contains other rect transforms
I believe they mean the parent RectTransform . . .
yea ^^
CanvasGroups attached to parents can affect whether or not you block raycasts
but the parents themselves don't get hit
CanvasGroups are awesome . . .
oh? been a while since i touched UI. could've sworn the bounds of the rect would extend the child but probably mistaken with something else..nvm my memory is bonkd
The RectTransform itself is immaterial
It just defines a region of space (which children can use to position and size themselves)
Oh okay.. Maybe I put one of those canvasgroups thingys and didnt realize
as soon as unity makes World canvas fully polished on UIToolkit it will soon be bye bye UGUI
so I asked Mr. ChatGPT to write a script that tells me what I click
Very helpful 👏
so what was the issue? also send the code it wrote, curious so see whats going there
A tool for sharing your source code with the world!
I was trying to be scarcastic
idk what the issue is
lmao
so there is no result on the button ?
none
thats not right, can you show inspector for your button then
wait the image is disabled ?
You need something to click on
Im not sure if this would be in the code place or artist place but ill try code. I have been trying for a bit now to add a collider to my terrain in my 2d platformer like my player. But it doesn't seem to want to function. Any suggestions to this issue would be appreciated. Ive tried to do a terrain collider but when i move around in the game, my player falls through the ground still.
not really a code question. Where is the collider on tilemap ? its missing ofc things will fall through
oh mb. i removed it since it wasnt working. what collider would you suggest to use? terrain, box collider?
the only collider you can use
Tilemap Collider *
noworries
I enabled it and made the image transparent and nothing changes
ill make sure my eyes work properly next time
even with alpha 0 it should be working if image is enabled
is the raycast all still not printing the name ?
Depends on the button's alphaHitTestMinimumThreshold
all of my weapons code is in there
yeah...
ah right.. forgot thats a thing, only be set throug code though no?
Add this line:
Debug.DrawRay(gunTip.position, shootDirection * bulletSpeed, Color.Red, 200f);
The line after you set the bullet's velocity. If you check back to the scene view after firing a bullet, you should see a line where it started, pointing in the direction it's supposed to go. Does that align with what you expect to be happening?
I believe so, but I don't actually know what the default value is
where do i put this ? at the very end ?
Unity is cursed
sorry im new
alphaHitTestMinimumThreshold defaults to 0; all raycast events inside the Image rectangle are considered a hit.
yeah seems to default to 0 so OP should be okay unless they change it
https://docs.unity3d.com/2018.3/Documentation/ScriptReference/UI.Image-alphaHitTestMinimumThreshold.html
It also doesn't work unless the texture used by the sprite allows for read/write access
i feel like we're missing something very obvious somewhere
it always does
Turn every single object off in the canvas. Add a Button object. Can you click on it?
istg you are right
on it, 1min
minimize the number of variables
Agree you should try slowly adding 1 by 1 and see whats happening
Okay random shot in the dark:
Does this button, or any if its parent objects, have the IgnoreRaycast layer?
if I disable a parent all children are disabled as well right?
ye
ok so apparently MainMenu may have something to do with it (plus the disabled image part which I fixed already)
the MainMenu is supposed to be the parent of the buttons
Do you have a panel on the mainmenu that covers the screen?
Here is the working tree, the buttons were inside the MainMenu directly
If you parented the buttons to the canvas and placed them before "MainMenu" in the hierarchy, then anything attached to MainMenu (or any of its children) would be able to block raycasts from hitting the buttons
Yeah I got a hunch its the panel thats blocking the buttons
notably, "MainMenu" is now also deactivated
activated it, still get detected
I see no reason for the buttons to stop working when parented to "MainMenu".
unless the MainMenu object has a Cavnas Group that turns off raycasting
custom scripts vs built in components
it had a canvas component
removed it
done now it works
im stupid
very stupid
ty very much
hm, that also shouldn't have, by itself, broken anything
unless the canvas lacked a graphic raycaster, I guess? I'm not too sure how that works
I think a canvas-in-a-canvas acts as a Canvas Group but with the added overhead of all the other canvas-y things
actually nvm
right, but that shouldn't cause any problems on its own
you should be able to raycast into that nested canvas
(I haven't actually used nested canvases much yet -- I probably should...)
ignore what I said earlier, apparently the buttons still dont work inside menu
I have a main menu that has many totally independent screens, but they're currently all crammed into one giga-canvas
I think a nested canvas may need a graphic raycaster too?
I'd expect so
so I moved the event system inside the canvas
and now the buttons work inside the menu
...what
the EventSystem component can live anywhere in the scene
I need you to show me the inspector for the MainMenu object.
so you've removed the Canvas from this object?
now show me the hierarchy
ok now it works with the event system outside the Canvas
but it didnt work before
neither EventSystem nor Debugger need to be in there
My brain is rotting
i added that line of code you gave me to the script , sorry if i did something wrong im new
now my listeners dont seem to be working, im supposed to be sent to another scene when I click on PlayController
You have to actually look at where the line ended up. Go into Scene View after firing a shot and look for the red line
ok so i think you want me to add a line in the players view to track down where the bullet should go ?
The DrawRay line I gave you will put a line in the scene view showing the bullet's starting point and direction.
Fire the bullet, switch back to Scene View, and look for that red line
Idk what this method is called, so i couldnt find it onlline, how does one achive no errors?
YDiference is a parameter of the CheckHeight method
There is no reason for that name to be valid anywhere else in your program
this makes no sense
what is CheckHeight supposed to do and why aren't you using the parameter you expect in it
if its a result , consider setting it as that value instead of void
Alr, i removed it but there is still the errorrr
yes because ur method expects a float
you have given it no float
You're calling the method without providing an argument for the YDifrence parameter . . .
parameters don't cause variables to appear for whoever called the method
CheckHeight wants a float. It then reassigns it (which does nothing) and exits
perhaps explain what you're trying to do with this method exacly, what are you comparing to
you could always return the float difference or bool result?
You need to pass it a value
Alr..
if you don't understand why your existing code is very wrong, then I'd suggest using !learn to figure out how to write C#
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
im trying to assign a bullet hole texture so i can know if the bullets are hitting walls or not , but it wont allow me to put it , please help
Texture asset != gameobject
just use decal projector
How can I make a serialized/public field only appear if a certain other serialized/public field is of specific value? Like, I have a bool isBot which changes some mechanics of an object, but some of them are not read even once depending on whether or not that bool is true or not. It's an inspector thing, but would make stuff much more readable.
You need custom inspector script
What should I do to make it work ?
Use the NaughtyAttributes plugin
You can also use NaughtyAttributes or put your bot settings in a struct/class variable
What's so naughty about them?
Hello, I need help with code.
Don't make scripts with the same name as Unity components
they are naughty because they contain attributes unity should've been added
most of the stuff there is pretty much stuff unity has built in like MinMax slider
Thanks
Damn! These look really helpful
yeah they are good, but tbh its a lot to add if you only need 1 or two just build it yourself to minimize dependencies
Well it beats needing something like Odin, especially one for [button]
maybe I just enjoy editor scripting a bit more so I try to always build my own lol
yes its basically free version of odin but gimped a bit
I think for the majority of cases, that's all you really need
Especially for very general purpose things you'd want to get the inspector to do
yeah great for designers too
I'm in the UIToolkit rabbithole for custom editor windows, enjoyable tbh
same here nav. I love UITookit for its easy to use visual interface. I love coding, but when it comes to showing things the user ACTUALLY sees, uitookit is way too good, for its use. I just hate that it waited SO long to give us runtime binding
yeah UITookit just felt more natural for editor tooling, I'm guessing this was them then thinking "why not also put this as ingame UI" ? maybe idk lol
layouting and css styling options help out a ton though.
I havent fully used the uxml yet though (I hav kinda disgust from xaml styles)
you can do everything in c# so its nice making premade components for styling . I'll change this once I work with some layout artist
i havent like coded the umxl (css stylesheet with selectors right?), as its a large learn curve, but i use it for grouping related elements, or elements that need to be affected by the same thing, like the same thing as a prefab and variants
my first one was a basic dynamic scroll list lol
ohhhh yeah, i love the prebuild lists, but some of them need to be editable after the fact, like for example you cant edit the input fields in the uitookit (i mean the editor window, had to use code)
have you use the builder yet ?
opps maybe we should move it to #🧰┃ui-toolkit
This is what I want to do, I just need to understand the underlying code to access the container elements and the actual value . . .
yeah tbh it was easier at first to do this via c# if the component is defined there, I found databinding to be a bit more difficult from c# since they gave no clear instructions for it at the time, it was basically a bunch tree queries for the property to bind to
that all feels a bit confusing to me right now
Hello I’m new to unity, I downloaded a 3D Character from the unity asset store and I wanted to ask if I can use it to animate in blender?
Or use a the character and apply Mixamo animations on it?
If it’s possible can anyone please help me with what to do?
Start googling some tutorials, and if you have any specific problems then ask in #🏃┃animation
did you also add the birdIsAlive condition?
Is it possible to generate a navmesh via code that includes bidirectional offmesh links?
The NavMeshSurface has an option for "GenerateLinks" which doesn't appear to be public, nor does it seem to have an option to include Bi-Directional.
Would be silly if you couldn't buttttt if you can't I can assure you that A* project does
Would be a pretty big update I'd have to do to swap to it sadly. Project is already fairly far along.
I have a DOTS RigidTransform with local values as an offset how would I go about converting that to the world positions based on a provided world position?
Hey, sorry if this is completely a "I know nothing, help me" question, but does anyone know any good tutorials for creating a camera system? Right click on an object, it acts as you 'taking a picture', maybe displays a line of text for a second, then activates something else? Similar to the game Amenti if anyone's familiar? I'm trying to learn my way through making this game, and I can't seem to find a good tutorial for this kinda thing
You'll want to read about RenderTextures
If you want to do a sequence of events like that, you can look into coroutines.
You can tell a Camera to render into a RenderTexture, rather than to the screen
As someone who knows nothing about either of those, what's a good place to start? Just googling "unity rendertextures" and going from there?
You can start by creating a RenderTexture asset, plugging it into a material, and then assigning it to a Camera
I'll check them out, thank you!
You can disable a camera and then call the Render method on it to make it draw once
Wait that would be really helpful
Do .Bounds work for 2D colliders or better use overlapingPoint?
i'm not sure what you're asking about here
Collider2D does, indeed, have a bounds property
you can then check if this bounding box overlaps another bounds object
(and this does work properly in 2D, as long as the two bounding boxes are on the same plane)
I am asking if I want to check if a point is inside a 2D collide, would be better to use .Bounds or overlappingPoint
Since they... Kinda seem the same for this?
you mean OverlapPoint?
oh hey, I didn't know that existed. neat.
You would want to use that.
The bounding box is very frequently not equivalent to the space taken up by the collider
that's only the case for a non-rotated box shape
Oh, so overlapPoint is for the bounding box only or how?
No. OverlapPoint tells you if a point is inside the collider.
The bounds property gives you an axis-aligned bounding box that encloses the collider
This almost always covers more space than the actual collider
I imagine that OverlapPoint starts by checking if the point is inside the bounding box
and, if it is, it then does more complex math to decide if it's actually inside the collider
There will be situations where your point is inside the bounding box, but outside of the collider.
imagine a circle shape: you can enclose it in a square. that's the bounding box
there are points in that box that aren't inside the circle
also if you want to detect arbitrary objects, checking the bounds would definitely not be the way to go or else you would need to reference all of the possible objects and check the point for each of them, if you just want to know what your cursor is over (which i'm assuming this is still about that) then the overlap point is the better option
that'd be Physics2D.OverlapPoint
I just discovered that Collider2D.OverlapPoint also exists
But yes -- if you are querying for colliders at a point, you want to use Physics2D.OverlapPoint
Otherwise, you'd need to walk through every possibly-relevant collider and ask each one if there's an overlap
right, and Physics2D.OverlapPoint is what i suggested to them last night
I couldn't quite tell which one was being talked about
the question appeared to be about testing a single 2D collider
yeah 2d physics has some neat quality of life stuff built in. you can directly cast a collider (if it has a rigidbody on it), you can to a single axis of velocity, and these other overlaps/casts
Ah, so if I want to check if a point is, for example, inside like a star shaped collider, I should check for overlapPoint right?
Cause Bounds would not be accurate
Kk
I must clarify here: which of these are you doing?
- Checking if a single, specific collider contains a point
- Checking if any collider contains a point
I am dragging a 2D object inside a 2D collider area, in way that if I move the cursor outside the area it just stays as close to the cursor as possible within the area
Does that make sense?
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Collider2D.ClosestPoint.html
This will tell you the closest point to an input position.
Oh, so the closestPoint must also be for 2D?
Oka
I was using 3D until now cause I didn't know how to do it in other way
wait, were you still using 3d colliders even after the discussion last night where i informed you that was entirely unnecessary for 2d and how to detect colliders using the Physics2D class?
No, I just did not change it yet, since I went to sleep
I was also coding some other stuff too in the meantime
Hi all - I am having trouble with player movement; it seems to be slippery? I have code like below which works to keep the player in bounds if I move him slowly. If I press hard on the directional keys though he can gian enough momentum to go out of bounds which then means he can't move at all. Would anyone mind pointing me to relevant docs or letting me know why this is happening? Thank you so much!
void Update()
{
horizontalInput = Input.GetAxis("Horizontal");
if (transform.position.x > leftXRange && transform.position.x < rightXRange ) {
transform.Translate(Vector3.right * Time.deltaTime * turnSpeed * horizontalInput);
}
}
i wouldn't expecting "pressing hard" to do anything
keyboard input is binary
unless you have one of those weird pressure-sensitive keyboards
You're probably just confusing it with GetAxis having smoothing vs GetAxisRaw that has no smoothing
Ok, I am gonna fix what I am doing first and I was just seraching for a LookAt equivalent for 2D; and I found u kinda have to caculate the rotation manually? Is that right?
you can assign to Transform.right or Transform.up
I found this, while for 3D would just be LookAt("point you want to look at")
I found it kinda weird
simple enough
var dir = b-a
transform.right = dir
You can assign transform.up or transform.right to a direction and it'll point in that direction
So I'm new to Unity and especially to using coroutines, and I'm tryna make a slowmo powerup. For now I just want it to initially drop to timescale=0 really quickly as a first step, and it just doesnt work.
The console outputs "Dropping time scale" only once and then nothing happens.
The ActivatePowerUp() function is called from another script when I pick up the powerup, and its called exactly once, so the problem's not there
I just feel like there's a really stupid mistake here somewhere but I just dont see it😭
And don't ask why my base timeScale is 1.15 lol
Hi Everyone - About three months ago, searching through addons for helping in game creation... I decided to take a challenge and write Unity code from scratch through a Udemy coarse on C#. A few months later I'm happy that I did, because I know every line of code and what it does which makes me feel more in control of my destiny. I'm a noob and I'm hooked on development now. Was scared to delve in, but now... I can't wait to learn how to write a new Class.
i have a for loop inside an IEnumerator with a few WaitForSeconds in it. How would I quickly stop everything inside the coroutine and start it again from the start?
StopCoroutine exists
Im a complete noob myself but probably just StopCoroutine() and StartCoroutine()?
With all that said... Most of the courses I've been training in was written using Unity 2018... I decided to code in Unity 6 against all advise, but to hell with it... I went for it anyhow and my code works after asking CoPilot for some help. Don't care what anyonw says negative about AI anymore... dang Artificial Intelligence is freakin awesome.
i have tried this, but for some reason the WaitForSeconds keep doing their thing from the previous time when i start it again
One thing though... FindObjectsOfType was completely changed in Unity 6 to FindObjectsByType with some added stuff... but... I got through it
I'd use the debugger to figure out what the values are at each step and what's going wrong in relation to your expectations
God I wish it didn't throw
yeah that's silly, it should just do nothing if null is passed. or at most log a warning
Alr but its just really confusing. Its a really simple while condition, just if timeElapsed is less than dropDuration
It should at least send another debug log (the "Dropping time scale" one) but it doesnt happen
Make sure you don't have Collapse enabled in the console. Then go through this https://unity.huh.how/coroutines/disabling-objects
is there any links to completely start unity c# as a beginner?
It says "1"
When something is logged multiple times it changes the number and I havent changed anything in the console
there are beginner c# courses pinned in this channel, and the pathways on the unity !learn site are a good next step
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
thankyou thats perfect
Your public void ActivateThePowerUp() - What is calling this? Is it only being called once? I don't see the rest of your code and classes. Does something need to be in an void Update() which calls every frame
I'm curious, why did you screenshot the console text, along with 90% empty space
Because otherwise you either would only see the number 1 or wouldnt see it
It was the point, that the message is only logged once
It's possible the shrink the width of the console
this doesnt fix it
show what you tried
But its faster to just screenshot it as it is
I suppose so
Take your dropDuration from 0.2f and set it to 1.0f and just see what happens. Does it do anything? Sometimes I will adjust the values as a way to debug.
Time issues
Pls help if somebody knows😭 I literally dont see the issue
The while condition should return true, I debugged it and it says:
timeElapsed = 0.006944451, dropDuration = 0.2
Yet the entire coroutine just stops executing after running the cycle once
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
Look at your math you have timeElapsed set to 0 being divided by 0.2f... is 0
Nvm, its such a stupid mistake lmaooo
Finally figured it out
I can only presume you're disabling the GameObject
Set your timeElapsed to 0.05f and go from < to <= and just see what happens
I was destroying the game object that held the script
Yep
And the reason I did it is because its a powerup, its supposed to disappear when you pick it up
lol
after stopping it and starting it again, it continues showing text from the previous time
Ah that would do it
have you confirmed you are actually stopping it?
The ole "destroy game object" - that happened to me too... really was frustrating. Trying to figure out code... But Hey - We are learning right?
Yeah, its really satisfying fixing something like this even if it was this stupid
I've spent time pulling my hair out looking at my code... only to relized... I forget to attach the script to the game object.
I was getting so frustrated
It's fun though finding the solution.
Simple debugging techniques will save you from this! Debug.Log! Check your assumptions!
In my specific case they didnt help, I was destroying the object in another script and didnt even think of it😅
Now I know its probably better to disable the renderer or smth rather than destroying the object, unless I'm certain I want it destroyed
Well if a coroutine stops running there are only a couple possibilities - a destroyed object being one
Now I know
I'm just beginning to comprehend coroutines
each MonoBehaviour has a list of coroutines it's handling
hence why you have to call StartCoroutine on a specific MonoBehaviour
I want to get a reference to this script that I downloaded to enable and dissable it, but apparently it doesn't show? How can I get access to it?
what do you mean by "it doesn't show"?
Like.... it's not in the collection of namespaces?
I am guessing I have to do a "using Something" but not sure what
That's exactly what I am asking, what I am looking for there?
I am not familiarized with that stuff
ScriptableObject is not showing up as a ScriptableObject in the inspector/editor/other scripts (name of script is ItemInventory)
ive been coding for years, and this just, just stumps me
It needs to be the first or only type defined in the file
the UiBuilder has it this way, so i thought the code would be correct
but thank you so much
Also the create asset menu attribute is on the wrong type
ah gotcha, thank you
its still considered a MonoScript, and cannot be selected as a scriptable Object
MonoScript is literally the type of asset for the actual script file. you can create the SO instance from the Create menu
.... its legit an asset, that i havent thought to make.
thank you for educating me.
Could I make something like... use a CompositeCollider as a mask layer for a sprite?
I want to make the area defined by it to have like sorta of a tint
Do I have to do that manually?
thanks for the suggestion - I tried switching it up but I am still having the same problem. If I have a range for player movement as -4 to 4, I would expect that a player can move only within that range. However, for some reason the player can get to -4.04, (not this value consistently, sometimes it's like -4.1), and then at that point they are no longer able to move. Anyone had similar problems??
There's nothing in your code clamping them to the range of -4 to 4
You are moving the player AFTER the check
Colliders have nothing to do with rendering by default, so you would need to implement it manually. For example, generate a mesh out of the collider and draw it with a mask shader(would need to implement it too).
So what would be the best way to have a mesh for both a 2D collider and a sprite mask?
I could make one different mesh for each, but seems like a massively hassle to scale properly from outside unity
Well, you can use a polygon collider to define the vertices. Then generate a mesh from the same vertices.
With other collider I'm not sure. They might or might not have a similar data structure.
How would I generate a mesh from that?
thanks so much! Looked that up and now it's behaving as expected.
you can get the vertices from the composite collider using the pathCount property and the GetPath method
But... that's through script?
yes, this is a code channel that should have been implied
Seems that making a script to calculate those shapes for each and work and then trasnlate it to a mask would be even more complex than making it manually
If it wasn't intended to be a code question or wanting a code solution, maybe it ought to have been placed elsewhere? 
Where do I ask how to get a very specific and editable shape for both a collider and a mask?
Try #💻┃unity-talk if you're not sure
hi my pause menu is not working i need help
!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 #854851968446365696
pay particular attention to the last points (including the fine print)
i honestly just need to know if this code is broken or not its like 2 lines
Set Cursor.lockState to CursorLockMode.None;
Cursor.visible = true;
well that first line isn't even valid c#
there are beginner c# courses pinned in this channel if you do not understand how to assign a value
Where did you even find that syntax?
hell
the 1 answer
that's not at all what you have
Okay but where in that question do you see that first line
okay basically im using the freelookcamera cinemachine camera for my third person game, but i dont really know how to adjust the values through code considering its an extenral package and i dont have access to it's class. specifically i have a camera sensitivity slider in my menu. how can I make this affect my cinemachine camera?
You can use the classes normally as long as you have a Cinemachine namespace using statement in your script, which is conveniently displayed in the documentation https://docs.unity3d.com/Packages/com.unity.cinemachine@3.1/api/Unity.Cinemachine.html
Typing out one of the classes and using your IDE's quick suggestions/fixes or right clicking a component, clicking "Edit Script" and looking at the code are also options.
hii im making a local multiplayer game and Im having trouble with my gamemanager script calling an UpdateTimer() on my playerscript. Each player has their own timer UI but the timer itself is being run on my gamemanager script (its split screen). I'm getting a null exception on:
//Player Script
public void UpdateTimerUI(int timer)
{
timerText.text = timer.ToString();
}
Thats being called from this:
//GameManagerScript!!!
IEnumerator UpdateTimer(int seconds)
{
int count = seconds;
while (count > 0)
{
yield return new WaitForSeconds(1);
count -= 1;
foreach (GameObject p in listOfPlayers)
{
p.GetComponent<PlayerScript>().UpdateTimerUI(count);
}
}
gamestate = GameState.End;
StartCoroutine(EndGame());
}
void StartGame()
{
gamestate = GameState.Running;
StartCoroutine(DelayedStartTimer());
//GameVisualManagerScript.instance.DisableTimer();
}
IEnumerator DelayedStartTimer()
{
yield return new WaitForSeconds(0.1f); // Give PlayerScripts time to initialize
StartCoroutine(UpdateTimer(timer));
}
I have a delay because I feel like its got something to do with the ordering of the Player's Prefab Start() and thought it would help but it didnt, not sure the fix
Looks like timerText is null. How are you assigning it?
in my player's Start()
private void Start()
{
myStats.score = 0;
myStats.lap = 1;
myStats.stunned = false;
myStats.firstLap = true;
myStats.finishedTrack = false;
playerCamera = GetComponentInChildren<Camera>(); // Find the camera in the prefab
//playerIndex = GameManagerScript.instance.AddPlayer(this.gameObject);
//AdjustUIForPlayer();
myCanvas = GetComponentInChildren<Canvas>();
scoreText = myCanvas.transform.Find("MoonshineScore").GetComponent<TextMeshProUGUI>();
lapText = myCanvas.transform.Find("CurrentLap").GetComponent<TextMeshProUGUI>();
timerText = myCanvas.transform.Find("Timer").GetComponent<TextMeshProUGUI>();
Debug.Log(timerText.name);
UpdateUI();
UpdateTimerUI(60);
}
That log should be throwing too if it's null
its not though, the timer works fine on the player script and anything its being referenced in there
Can you send the full error message
I am starting the StartGame() function that chains the coroutines in my GameManager script once the player count reaches 2:
public void AddPlayer(GameObject player)
{
listOfPlayers.Add(player);
if (listOfPlayers.Count >= 2)
{
StartGame();
}
}
which is fired from the new input system's detecting a player joined
one sec
im like 99% sure its this weird internal thing with how the player's Start() works in the innerds of Unity since the player is a prefab that gets instantiated by the New Input system detection thing, but im not sure how to fix it
Yea I imagine that Timer text should have popped for each player object instance. One potential fix could be to switch from Start to Awake to initialize these fields earlier.
alls I did was change Start to Awake and it didnt work :C
you're passing the prefab to the GameManager's AddPlayer method, not the instantiated player
the PlayerJoinedEvent passes the PlayerInput instance but you are throwing that out and passing a prefab instead. and since prefabs don't exist in the scene they've never had Start or Awake called on them so any variables initialized in those methods are still their default values (which is null for reference types)
null for reference types... that makes sense
i sincerely hope that isn't the only thing you took away from all of that
the PlayerJoinedEvent passes the PlayerInput instance but you are throwing that out and passing a prefab instead
What does this mean tho
i was thinking!
:/
that means you are not passing the spawned object, you are passing the prefab
i didnt know there was a difference... How do I fix it though? The reason I added that parameter was so I could store it in the list
passes the player input instance.... how do I reference that player input instance then instead of the prefab
the PlayerJoinedEvent is a UnityEvent<PlayerInput> which means when it is invoked it will normally pass the PlayerInput reference to the listeners, but you have added a listener that does not accept that object and instead have selected to pass the prefab.
The method you are subscribing should accept a PlayerInput parameter (which you can then get the gameObject from if that is what you need from it) and you need to subscribe using the Dynamic option
https://unity.huh.how/unity-events/dynamic-values
oh so the actual prefab's playerscript component into that ?
no, that is not at all what i said
how do i change centre of mass of a 2d sprite guys?
there is nothing there
wdym there's nothing there? i linked directly to the documentation for the relevant property that does exactly what you asked about
The prefab you put in the button isn't the one used at Runtime, you're using the prefab that's in the assets folder.
You neede to put in the object that's present in the hierarchy
hello everyone, im new to unity and im following the rollaball tutorial. just reached the movement creation part, i did everything as the instructor said but my ball is not moving like hers
mine is not moving at all
show relevant !code and the relevant scene objects
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
Make sure you check the Console for any error messages
yo hello, I am new to unity and started on the Roll-A-Ball game as instructed by my instructor. I just coded a new feature in my Roll-A-Ball game, basically its a timer feature that would spawn the enemy. However, when the enemy spawns, it isn't being destroyed once the game is won and doesn't follow me around. Don't know exactly why it stopped working. Here is what its looking like:
Enemy is a Prefab so that it spawns
EnemySpawner Empty GameObject is used for a place on where is spawns and also has the script attached, which is responsible for the timer. If i input 3, then in 3 seconds, the enemy will spawn. But the thing is that it doesnt follow around me anymore, nor, dies when game is won.
this is the console
video includes all scripts, and demo
Let's create a simple script using prefabs and a timer to spawn endless waves of enemies for our Unity game.
thats what i followed
if you prefer text here is it:
EnemySpawner.cs```
using UnityEngine;
public class EnemySpawner : MonoBehaviour
{
public GameObject spawnedEnemy;
public float timeToSpawn, spawnCountdown;
void Start()
{
spawnCountdown = timeToSpawn;
}
void Update ()
{
spawnCountdown -= Time.deltaTime;
if (spawnCountdown <= 0)
{
spawnCountdown = timeToSpawn;
Instantiate(spawnedEnemy, transform.position, transform.rotation);
}
}
}
it has no error
and everything is linked appropriately
my inputactions file
In your screenshot of the code you can see OnMove is greyed out slightly- This is Visual Studio's way of telling you that the method is Unused, meaning that there's no other code calling it (so it never runs).
I suspect this could be part of the reason it's not working?
how do i call it
I would hope the tutorial would explain that at some point :D
it doesnt
hi, very new to unity. Im trying to create a script which drags 2 objects at the same time and returns them to the original position once the mouse is let go.
Cant find anywhere that does that
they just write and the code works
Sorry, I was reading the transcripts of the tutorial :)
It looks like the PlayerInput script will "magically" call the OnMove function for you with the correct input- This seems to be some nice helper stuff they've got going on for beginners.
That all seems fine though
show the inspector for the rigidbody. also read the bot message about sharing code #💻┃code-beginner message
just store the original positions and assign that back to the transform.position after releasing the mouse (or move them towards it in update)
alright, ill try that
so i delete the xrcontroller
that is not the issue, you have 4 bindings in your Move action, that is just one of them
they have a WASD binding on the Move action
there it is, the rigidbody is kinematic so it isn't affected by forces
exactly i think unity is supposed to automaticaly choose which input i have
shukraaan its workingg
that is one of the advantages of the input system's action maps, you can set up multiple bindings for the same action for different input devices and it can detect the input from all of them
so anyone got any idea on how to fix my issue?
A tool for sharing your source code with the world!
for some reason even if i give the correct name for the script to run off of the multiplier and streak wont show up on the hud
check your console for exceptions
When you create your enemy you need to pass in the instance reference of the player
You are referencing the prefab, which is like a template. You need to reference the one that is used during the game
there isnt anything in the console :(
screenshot it at runtime when this code is not working
But also, where are the PlayerPrefs values being read and displayed from?
( This feels like a typical job for the Debugger. Slap a breakpoint in your scripts and see where the call trace takes you )
and is the GameManager object entering a trigger to cause that ResetStreak method to be invoked?
I am getting a weird error and i do not understand what it means "SetDestination" can only be called on an active agent that has been placed on a NavMesh. UnityEngine.AI.NavMeshAgent:SetDestination (UnityEngine.Vector3) Enemy:Update () (at Assets/Scripts/Enemy.cs:31)
also you assign 0 to streak right before calling UpdateUI which then uses the value of streak to set the player pref
your NavMeshAgent is not touching the navmesh
or it isn't active
but it works D:
oh wait i think i understand
bcz its on enemies, and when i kill an enemy it dissapears
i have a like if(player != null)
{
enemy.SetDestination(player.transform.position);
}```
lots of ppl said setting the value to "-1" can actually turn the checkboxes off, but when i did that with code, i cant
how can i turn off the active checkbox
wait that only works on width??
strange
If we look at it in debug mode -1 is the default so must be something else you did
private void Update()
{
if (recordCount != textCount)
{
GetComponent<LayoutElement>().preferredHeight = -1;
GetComponent<LayoutElement>().preferredHeight = GetComponent<RectTransform>().rect.height;
recordCount = textCount;
}
}```
this script will run in editor mode
and it is the only thing affecting the preferred height
if the rect transform's rect.height isn't -1 then naturally that would result in preferredHeight not being -1
the resetstreak method is working fine
the object is below the notes
- how have you confirmed that
- read the next message i sent
i just ran it and missed a note after getting atreak
i found out the problem, it was the checking lol
this just came up[
doesn't seem relevant to the issue you've described so far, but you can use this to troubleshoot it: https://unity.huh.how/runtime-exceptions/missingreferenceexception
turns out im just a melon and didnt reference it whenever I updated the streak
but thank you for the help
simple as that
that is not what a reference is, that is simply calling a method. and for future reference, you should provide much more detail about what you expect to happen since all you had said was "streak wont show up on the hud" and you were only updating the value stored in the player pref when OnTriggerEnter2D was called i assumed you wanted it to only update after that point
Unrelated but code like this could be turned into quite an easy one-liner: https://dotnetfiddle.net/1LAORN
guys can anyone help me fix this pls
Complain to whoever made that asset, or double check that you have the correct version of photon vr installed for that asset
i do have the right photon vr
Is GcsWardrobeButtonManager your script?
and plus i cant complain to the owner of it becuase he banned me
no i found it in discord why
trust me dont beg and ask for help he doesnt like it
My recommendation then would be to learn C#
how tho because im not good at learning scripts
You don't "learn scripts" .. you learn the language (C#). !learn 👇 and see pinned msgs
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
i dont get it
Because the problem is in that script, because it doesn't know what Saving is from Photon.VR. Either it used to exist in an earlier version and was removed/renamed or it just doesn't exist outright.
I don't literally mean a file named Saving, look up how namespaces work in C#
wydm
It can't find a type or namespace named Saving in the Photon.VR namespace. If you don't understand what that means, you need to learn the basics of C#
soo how do i get the saving or do i deleted the saving in the script
so i deleted and now i got 18 errors
Deleting it is not the right approach, if the API has changed you need to update the script to the new API
how do i update it
You need to do some research on the new API, again I'm assuming that. I don't actually know if Saving in that asset even exists.
oh man
t:material shader:Universal Render Pipeline/Lit"
i want to search for materials that are lit , how can i do this in editor ?
this doesnt seem to work
can anyone let me know how this works?
It looks like it does exist, assuming this is the asset you are using.
https://github.com/fchb1239/PhotonVR/blob/main/Saving/PhotonVRValueSaver.cs
So either you don't actually have the asset imported into your project, or you have corrupted it in some way
download the .unitypackage and open it
Hello, trying to create a main menu for my game. For some reason my OnClick won't work for my buttons. I have tried everything on the internet with no luck
The button seems to be clickable
will it reset it
not really a coding question
You need to provide more info, code, screenshots, etc.
can i have some help and pls
i need help with installing unity on linux
my unity goes not responding forever on splash screen. and it doesn't show me any error message.
the version is Unity-2023.2.20f1. and operating system is Ubuntu 24.10 Oracular.
Okay now it actually seems like it was already in your project and is now imported twice.
how
and the first version was corrupted
ok i deleted it and now i got 10 error
My other guess is that your GcsWardrobeButtonManager is in an assembly definition and does not have a reference to Photon.VR
it was the first one there was 2
This is my working tree:
Buttons are interactable, the text meshes inside them do not have raycasts
I added a script to the MainMenu object which contains the functions the buttons should call when clicked and attached the functions to button OnClick on editor
I created the debugger object to attach a script which tells me which button I click (previously the buttons were not even detectable)
Some more info, when I am on Play Mode, the EventSystem won't say anything on **Selected: ** no matter where I click
if you need more details, please let me know
shader?
I would say #💻┃unity-talk because it is just a question about how to search the editor
ok thanks
u still here??
I have to get ready for work, so that is all the help I can provide for now, good luck
ok
why am i not able to trigger animation:
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class NewBehaviourScript : MonoBehaviour
{
[SerializeField] private float move_Cat_Speed = 0.4f;
private Rigidbody2D rb;
private Animator anim;
private GameObject player;
private bool isPlayerNear = false;
private bool isAnimationRunning = false;
private float catXPosition;
void Start()
{
player = GameObject.FindGameObjectWithTag("Player");
if(player == null)
{
Debug.LogError("No");
}
rb = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
catXPosition = transform.position.x;
}
void Update()
{
if (isPlayerNear && isAnimationRunning)
{
float playerXPosition = player.transform.position.x;
float xDifference = Mathf.Abs(playerXPosition - catXPosition);
if (xDifference >= 2f)// Cat walking animation stops once the condition is met
{
anim.SetBool("cat_walk", false);
isAnimationRunning = false;
}
}
}
public void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Player") && !isAnimationRunning)
{
anim.SetBool("cat_walk", true);
isAnimationRunning = true;
isPlayerNear = true;
}
}
public void OnTriggerExit2D(Collider2D collision)
{
if (collision.CompareTag("Player"))
{
isPlayerNear = false;
}
}
}
// The cat walking animation triggers once the player enters its collider and the animation happens only once, doesnt repeat again if the player triggers the collider again```
You have two conditions and two booleans and they're conflicting with each other. You'll have to decide if you want to stop the animation when the player leaves the trigger, or when the player is 2 units away, and remove the other one. Or if you want both conditions then the conditions in Update need to be redone.
Why did you write it like that in the first place? I'm having a hard time understanding the logic there.
So do you want both of those conditions? Is it that both have to be true or that either one has to be true?
Can't you do without the Update method all together?
both
Then the condition should be if (!isPlayerNear && isAnimationRunning)
// The cat walking animation triggers once the player enters its collider and the animation happens only once, doesnt repeat again if the player triggers the collider again
I assume this is the task?
Wouldn't the OnTrigger methods already fulfill this?
lemme check
Well, you'd have to set anim.SetBool("cat_walk", false);in OnTriggerExit
As long as you have exit time ticked in the animator, I believe it should play until the end before stopping.
That would ignore the > 2 units away condition
yup
So in what way does it not work now?
the walk animation doesnt get triggered at all, it's at idle animation even after the player enters the collider
the animator is set correctly.
Not even the first time?
The walk animation
nope
What did you change in the code?
And if you remove the ! again does the animation work?
You're not making it easy to help you
lemme tell u, apart from the code
what i did
and maybe then u can find the fault
and help out
- Made the cat idle and walk animations, made transitions to occur depending on cat_walk
Just show the code
- Added a 2d rectangle trigger to cat that looks like this:
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class NewBehaviourScript : MonoBehaviour
{
[SerializeField] private float move_Cat_Speed = 0.4f;
private Rigidbody2D rb;
private Animator anim;
private GameObject player;
private bool isPlayerNear = false;
private bool isAnimationRunning = false;
private float catXPosition;
void Start()
{
player = GameObject.FindGameObjectWithTag("Player");
if(player == null)
{
Debug.LogError("No");
}
rb = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
catXPosition = transform.position.x;
}
void Update()
{
if (!isPlayerNear && isAnimationRunning)
{
float playerXPosition = player.transform.position.x;
float xDifference = Mathf.Abs(playerXPosition - catXPosition);
if (xDifference >= 2f)// Cat walking animation stops once the condition is met
{
anim.SetBool("cat_walk", false);
isAnimationRunning = false;
}
}
}
public void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Player") && !isAnimationRunning)
{
anim.SetBool("cat_walk", true);
isAnimationRunning = true;
isPlayerNear = true;
}
}
public void OnTriggerExit2D(Collider2D collision)
{
if (collision.CompareTag("Player"))
{
isPlayerNear = false;
}
}
}
// The cat walking animation triggers once the player enters its collider and the animation happens only once, doesnt repeat again if the player triggers the collider again```
this is the code.
Ok and in the original code you showed earlier, // The cat walking animation triggers once was what happened?
is there any better way to do this then a cast?
Im trying to utilize a enum
same code with this change !isPlayerNear
Not really. Keep in mind enums are a way of defining a custom type.
Not really. You're using the int associated with the enum . . .
ah, thank you
That's not what I asked
then?
In the original code that you showed earlier, did the cat walking animation trigger once?
nope
the cat_walk bool gets checked and un-checked in the animator window during the game
!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/, https://scriptbin.xyz/
📃 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 doesnt get re-checked even after the player re-enteres the collider area
Ok so the comment you wrote there was basically a lie
wait
that comment was to basically lets others know what the code was gonna do eventually
any idea why this doesn't work on a WebGL build? https://paste.mod.gg/pbxobeycbxhr/0 It returns the debug in line 38, meaning it can't see the text files in the streaming assets path for some reason
A tool for sharing your source code with the world!
T-T
it works perfectly fine in editor
also i made another fix to the code
Sorry, I don't have time or interest to try to dig for what actually is true or not when you're not able to give straight answers. Good luck
or u are polly dumb enough not to help and spend too much time focusin on the least prioritized comment rather than the main issue, exactly why i placed that comment at the very end of code and not in between the code.
I get that it can be uncomfortable not knowing certain things and having to ask for help, and maybe not receiving the help you need. But I think we should try to be grateful that there are people here at least willing to try.
Since this is mainly an animation related question, you might want to try posting in #🏃┃animation , there might be people lurking there with more ideas on what you can try.
Yeah that doesn't work here. We don't need to prove anything to someone who cannot spell the word "you"
No one here actually cares if your game works, we're doing this for fun, if you're gonna be difficult there's no reason to try
This is a great way to ask and get "free" help from those willing to spare their "free" time. It's a two-way street. You have to give in order to receive. Try following what people ask so they can best try to solve your problem. You're here in the first place because what you tried does not work . . .
Hello, here I am, AGAIN
So I found out that my buttons wont work specifically because of the new input system, when I use the old one in the EventSystem everything works.
Nothing is blocking my buttons....
Are you using a custom actions asset there?
The default one usually works best
it's the default one
Well it works in general so something else about your setup must be causing it
I'll bump this since it may have gotten lost in the drama lol. I'd greatly appreciate if someone could take a quick look
Would having the project use both input system be a problem?
It's weird to me you have some other main menu script on this GameObject
Shouldn't be but in that case why not just use the standalone input module if it works
would it create any problems in the future? My project is created for Android
Make sure that the input asset here is correct and all of your buttons are wired in to the actions you want them to be. This looks like the default, so if that's not working I wonder if it's not able to detect whatever hardware you're using for input? It should just be the mouse so I'm not sure why that'd be the case
is this screenshot your event system gameobject?
I saw it I just don't know anything about webgl, maybe try #🌐┃web ? They probably know more about what paths you have access to in a web build
I don't think you can use GetFiles with StreamingAssets in a compiled build, since it's not a directory but a compressed file.
What does android have to do with anything?
here is an updated one, with a recreated event system
Yeah so that wasn't the default before...
Still same issue though
i use the new input system with canvas on android and it works just fine
i use the new input system only however
How did you verify nothing is blocking
hello
I created a new scene, just with a a canvas with the button, panel and event system
anyone know how I can add a custom json to AddInventoryItemOptions
You're going to need to provide more info. AddInventoryItemOptions is something you wrote, not a unity function, and you'll need to explain what you mean by "custom json"
I believe it's from the Economy package
ya
trying to dynamically add json to a single type of inventory item from that economy package
Never heard of AddInventoryItemOptions. Mind sharing what that is?
I also.. asked ChatGPT to create a script I can use to output what UI object I am clicking
and it detects the buttons and stuff
Have you checked the docs here?
https://docs.unity.com/ugs/en-us/manual/economy/manual/SDK-player-inventory#AddInventoryItemAsync
The example for AddInventoryItemAsync seems to suggest you could just add your json string to the data.
Huh. Well I guess that at least demonstrates I am not qualified to answer this question
What’s the most straightforward way to accurately measure the execution time of a single function?
Trying to optimize a maze generation algorithm
thank you!
🤔 A Stopwatch maybe
One might call it, comedic timing
ba dum tsh
whats the easier way to duplicate an instance of a class? is there a unity method for it or like yea whats the most effective way, and i want them to be seperate not work as a pointer or whatever
Depends if it's a C# class or a MonoBehaviour class . . .
copy constructor
does the old input system work with touch controls?
Yes . . .
Good, what are the drawbacks of the old input system really?
its a interface class
namespace Minimax
{
public interface IState
{
List<IState> Expand(IPlayer player);
int Score(IPlayer player);
}
}
and the class im tryna duplicate is:
public class State : IState
ikr
then I will just use that since every possible tutorial out there uses the old system..
Thank you guys for all the help
Then it's working fine what makes you think it's not
because there is no hovering effect and the button is supposed to send me to another scene
which it does with the old system
I see. Also, it's just called an interface, not interface class. Since it's a c# class, as Mao noted above, you can use the copy constructor to create a copy or clone of the c# object . . .

this may be helpfull for POCOs https://learn.microsoft.com/en-us/dotnet/api/system.object.memberwiseclone?view=net-9.0&WT.mc_id=email
the "unity method" would be to serialize a class instance, then deserialize the resulting data back into a new instance of the class
This will only preserve fields on the class that are serializable by unity, of course, and it won't preserve references to any other objects
so just State stateCopy = new State(stateOriginal) ?
Right.
Note that you'd need to know the exact type here
You wouldn't be able to just do IState copy = new IState(original);
If you need to be able to clone any IState, make it implement ICloneable
can someone tell me why for a split second when i call this method i see the No Cameras Rendering
https://hastebin.skyra.pw/gesozuzipi.csharp
is there a moment in this code where no scene is loaded?
if so how can i fix that
u can see after i host the game its there for a split second
from what I gather I can't ~~read ~~ find these text files in WebGL, at least not the same as on Windows where I just check the folder?
https://docs.unity3d.com/Manual/StreamingAssets.html
On Web, Application.streamingAssetsPath returns a HTTP URL that points to the StreamingAssets/ path on the web server. For example, http://localhost:8000/unity_webgl_build/StreamingAssets/ is returned when your application is running against a local development server.
It looks like you'll use UnityWebRequest to fetch files
Note that if you just need text data, you don't need to use StreamingAsset at all
just chuck the files into the assets folder and reference them as TextAssets
yes, the file gets imported as a TextAsset
its just an asset you can get the text (or binary data) from?
thanks
and wow i had no idea
I've noticed that too lately, but usually I keep my main camera non-destroyable so I don't run into it much. In builds you wouldn't get the warning there's no rendering if you want to just ignore it.
so in a build it'll be black for a split second?
Possibly unless you need to clear any buffers?
Actually it may just keep the previous frame data
its probably the order im running the code, there is a moment where the scene hasnt loaded yet
Well, if the async is giving you the OK, I don't see what would be the problem
you mean after you start the game?
i fixed it
I don't see the "no cameras rendering" screen after you host a game
i'll show you how
its literally like split second
its barely visible
was
this is how i fixed it
just changed the order so that there is never a moment where some scene isnt loaded
how can i do that
sorry im really, really new to unity
just started like 2 weeks ago
You need to store a reference to the spawned instance
Say you have a GameObject myPrefabObj
You spawn an instances of that
var myNewInstanceObj = Instantiate(myPrefabObj);
Now, when the game is over, you destroy your spawned instance
Destroy(myNewInstanceObj);
okay so basically, instead of making an empty object to control the prefab, I actually use the prefab
correct?
This is the current code for the timer spawn feature:
using UnityEngine;
public class EnemySpawner : MonoBehaviour
{
public GameObject spawnedEnemy;
public float timeToSpawn, spawnCountdown;
void Start()
{
spawnCountdown = timeToSpawn;
}
void Update ()
{
spawnCountdown -= Time.deltaTime;
if (spawnCountdown <= 0)
{
spawnCountdown = timeToSpawn;
Instantiate(spawnedEnemy, transform.position, transform.rotation);
}
}
}```
or
can add the EnemyMovement to the EnemySpawner game object maybe?
nope my second one doesn't work
GameObject newEnemy = Instantiate(spawnedEnemy, transform.position, transform.rotation);
newEnemy.GetComponent<EnemyMovement>().whatever```
public GameObject spawnedEnemy;
This is a very confusing variable name.
You should name this "enemyPrefab" or something.
spawnedEnemy would be the thing that Instantiate creates
alright
EnemyMovement newEnemy = Instantiate(spawnedEnemy, transform.position, transform.rotation);
newEnemy.whatever``` 🙂
pretty rare needing to spawn something as GameObject
idk i just followed a tutorial and it just messed it up
so this part would replace this line correct?
Instantiate(spawnedEnemy, transform.position, transform.rotation);
maybe. I just got here lol idk what you're trying to do
if you want to access component from your spawned object then yes
this is all the context
really up to what ur doing
but yeah good point
true but pretty much every Component has access to GameObject property and Transform so it usually can just be accessed that way for things like SetActive or anything GameObject specific
Find + Update = bad
just store the player in the Spawner since thats part of the scene and should already have player there
[SerializeField] private Transform player
newEnemy.player = player
doing a Find each enemy spawn, especially by name is not very efficient
alright
btw make sure you put the prefab back in the slot after you change spawnedEnemy prefab to EnemyMovement
I've only been with unity for 2 weeks, and know almost nothing about the language or anything so thats why struggling a bit
also you should indeed change that name to enemyMovementPrefab
make it more clear what it is
😂
roll a ball tutorial is good but I feel like its skipping a lot of basics no ?
wouldn't it be better to do the Essentials pathways or the Junior Programming pathways first ?
https://learn.unity.com/pathways
yes but our teacher is requiring us to follow the tutorial, just to get the hang of Unity basics and stuff
ohh alright. Cause Unity basics stuff is pretty extensive ontop of knowing regular c#
Unity is basically an API
How should i go about referencing 7 more different skills in a similar manner to this? (for example, lets say i need to define "battle.nameText.text = battle.skill2.name;" and so on) cs public override void EnterState(BattleStateManager battle) { battle.nameText.text = battle.skill.name; battle.descriptionText.text = battle.skill.description; battle.attackIcon.sprite = battle.skill.attackIcon; battle.mpText.text = battle.skill.mpCost.ToString(); battle.healthText.text = battle.skill.healthCost.ToString(); }
pass in the particluar skill you want as a parameter
or store a reference to it as a field elsewhere and use that .e.g. Skill currentSkill
You can also use an array and keep track of what the current index into the array is
and you can combine these things
As a rule of thumb if you ever have a variable named with a number like skill2 you should be swapping those individual variables out for an array or a list