#💻┃code-beginner
1 messages · Page 579 of 1
do you have a component called PlayerMovement? (also it says PlayerMovement not PlayerAnimator)
yeah, a script i made, but it just shows up as new behaviour script
make sure the script's namespace is written properly
Its named New Behaviour script
Correct the naming
inside the script
that is not a component called PlayerMovement, that is a component called NewBehaviourScript that just happens to be in a file called PlayerMovement.cs
No problemo, keep going
This stuff is so difficult to learn
Programming or game development with Unity?
yeah. but i personally enjoy it
Both 😭
Complete beginner to both at 27
always thought it was cool! i started a quote-unquote indie game studio with my friend when i was younger (we had no idea how to code and just wrote shit down in notepad thinking our game would magically spring to life)
so yeah i think its fun learning unity ngl
Is there a way to have the UI buttons from the UI Builder appear in the Gamescene?
Mainly to make sure that I can actually interact with the buttons in-game.
!cs
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
Folks, How do I start with developing an Idle Tycoon game? Like what things to be kept in mind before starting?
how can i change the unity sample rebindactionui script to use tmpro
Be more specific in your question.
You need to think about hundreds of things whilst making a game, marketing, selling, support w/e.
Just make a game design document and see for yourself, but currently this question is way to broad.
Wouldn’t an idle game just be about manipulating numbers?
I meant in a programming way of things
Maybe I’m thinking of clicker games
Games like MyHotel have some npcs in there as well, where u make a room available, clean it, and then the customer can buy it
Clicking games yes. But with more to it
I’d probably start with the NPCs then, if it revolve around their behaviour. Make them move around and towards things based on certain conditions
Okay
how can i change the unity sample rebindactionui script to use tmpro
how do i add a refernce to text mesh pro in RebindActionUI.cs
Have you installed TextMeshPro?
yes
And what does the error say?
The type or namespace name 'TMPro' could not be found (are you missing a using directive or an assembly reference?)
Oh wait, you want to change unity build in scripts?
yeah its from a sample
In that sample, there might be a assembly definition file, you have to link TMPro in there, so that package knows, what TMPro is
this?
edit it in unity...
If you are using a asm def you add the reference to TMPro on that
the "auto" Assembly-CSharp does this all automatically cus you cant edit it. Using asm defs is better in the long run so good to get used to it
Be warned that old code or libs that dont have asm defs added cannot be referenced so you have to add them yourself 😐
My editor completely freezes when I call this method across a few hundred objects, is this expected?
I thought it could handle those collisions
i mean yeah that is a significant amount of work
Shit I'm running out of options to figure out neighbors for randomly generated cube objects (voxels)
Complete freeze doesn't sound reasonable though
Don't you save the voxels in some sort of grid data structure?
if they're on a grid, can't you just check directly without involving physics
I should have done that, I just kind of threw this together for an assignment
Never did procedural generation before xd
I was mostly just wondering about the freezing and crash when using that OverlapBox
// 3d adjacent neighbors
Vector3Int pos = ...;
for (int dx = -1; dx <= 1; dx++) {
for (int dy = -1; dz <= 1; dy++) {
for (int dz = -1; dy <= 1; dz++) {
Vector3Int offset = new(dx, dy, dz);
if (offset == Vector3Int.zero) continue;
Vector3Int neighborPos = pos + offset;
// ...
}
}
}
Every time you create a voxel, put it in some data structure that allows you to look them up later. In case you are making the scene out of individual cubes, you should definitely not in any actual product (generate procedural chunk meshes instead) but for quick and dirty assignment it would be fine I suppose
Yea for sure. I did the generation just purely with Random.Range values xd
There's nothing wrong with that. Just having thousands of individual cubes and scripts is usually not acceptable in terms of performance
Some sort of (pseudo)random values are always required for random procedural generation
How would I fix this? I'm using Sebastian Lague's Path Creator tool. I can use the path tool in the Unity editor, but I can't seem to get it to recognize the Path Creator namespace so I can use it in code.
regardless, OverlapBox should really be quite fast so the whole game crashing sounds like there's something else seriously wrong (like infinite loop). Where do you call this VisibilityCheck?
try reloading the editor, it might not be aware of the new namespace yet
Actually I broke something else because I commented it out and it still freezes
that's what I thought
Worked yesterday 
OverlapBox is definitely not the best solution but it shouldn't be that bad
If its freezing completely, its 99% a loop in your code it does not get out of
yeah, while, for or infinite recursion
infinite recursion would probably break eventually with a stackoverflow
although infinite recursion might actually cause an stackoverflow and not crash, i'm not sure
so probably not that
But without code, we wont know 😄
Yes it was infinite loop, I had messed with my tags and that had broken one of my scripts 🫡
fixed it , thank you
Welp ig i have to learn how to do C#
Because im making a game and i have 0 idea how C# works
To be expected when working with unity. Recommendation would be to take break from unity, do some basic C# (outside unity) and then get back to doing unity with C#
Only thing i know is probably print("Hello World") or something so im probably gonna need to learn from somewhere
There's also visual scripting but I would expect to find less resources/tutorials on it and some coding knowledge would be helpful on using it too
Where would you recommend i go to learn C#?
Check the Intro to C# tutorial pinnned on this channel
Yes, you could also follow any other C# tutorial out there but I expect that to be a good one, haven't watched myself
so im using the unity sample to rebind keys but whenver i rebind it it does not actually change the input key
Is this a beginner coding question? If not, try asking in talk #💻┃unity-talk
Else you'll need to procide more information.
I would assume so idk, i just used their script but it dont work
Could maybe be because of my movement code?
Not sure, you'll need to provide the necessary information (!ask - the last point)
: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
Quick question. Learning some new things with GameObjects and not using GetComponent() (instead just doing the Compoent component way), but having trouble changing the variable of another script this way. It did not work either when doing GetCompoent(), so I am unsure of why it is breaking. Where is the code to change the other scripts variable:
public void Start()
{
AddCardImage();
hand.handValue = hand.handValue + cardValue;
Debug.Log($"CardValue " + cardValue);
UISprite.sprite = cardSprite;
}
``` I DO get a variable for cardvalue, just hand.handValue always stays 0. Is there something I am doing wrong with this code? Do I need to show more info? Generally just confused at the moment.
you must be changing it elsewhere it wont magically change (unless handValue is a property with some logic in set)
btw you can do hand.handValue += cardValue;
put a break point before you set it and observe the before and after value
Oh hey! thanks for the tips yesterday. Let me check rq...
if its a property you can step into it if you are debugging to see what it actually does
and when i say "debugging" i mean attaching a debugger (https://unity.huh.how/debugging/debugger)
The debugger is a tool that halts code execution. Values can be inspected, lines of code can be stepped over, and sometimes even modified. This does not require recompiling your code, or exiting Play Mode.
If it helps real quick, here is all the code related to handValue. Very small
{
[SerializeField] public int handValue = 0;
public TMP_Text handValueText;
public void Update()
{
handValueText.SetText("HandValue: {0}", handValue);
}
}
``` Doing debugging rq, here the weird part - it keeps saying 100+?
plz use a debugger like i said. If the field is not the value you expect then it must be changed elsewhere or its not what you expect at the time of the addition
logs only get you soo far
what does it start at?
Also what's going on here? Are you spawning in a prefab or something?
print HandValue before and after updating it
It should always start at 0. Yep, spawning in a prefab (card) that has a value, and it should add its value to handValue
Will do
how does the spawned prefab get a reference to this script in the scene?
Methinks you are actually incrementing a variable on another prefab
not on the instance in the scene
Hope this is what you asked for? It's the HandPosition one
Prefabs cannot reference objects in the scxene
is this a screenshot of a prefab?
Like what script is this?
If that's a screenshot of a prefab then it must be referencing another prefab
It is, HandPosition is a prefab
look at the prefab
not the one in the scene
that's the value you are incrementing - the one on the actual prefab in your assets folder
So Im incrementing this one here?
Maybe? YOu have to check what you're actually referncing
you can click on the referenced thing and it will take you to it
You're either referencing the prefab, or an instance of it in the scene
Note when I asked "is this a prefab?" I mean "is it a prefab in the assets folder?"
things in the scene are not prefabs
They can be instances of a prefab, but not prefabs themselves
Yea easy for beginners to accidently modify the prefab asset and not an instance of the prefab.
im having some trouble with getting the mouse position as a vector3 im doing this atm
mousePos = mousePos - g.transform.position;```
to get the direction from my gameobject to the mouse but its not working as intended
Mouse position is a vector2
it's the position in pixels on your screen
you cannot directly do math with that and world space gameobject positions
They are in completely different coordinate spaces
so what should i do instead
when i instantiate my bullet so its transform.up to the vector between my player and mouse
is this a 2D game?
yes
Yeah, its referencing the prefab in the prefab folder. What I want it to change is the HandPosition here, should I reference it differently?
You need to convert the mouse position into a world space position. E.g.:
Vector3 mousePos = Input.mousePosition;
Vector3 mousePosInWorld = Camera.main.ScreenToWorldPoint(mousePosInWorld);
mousePosInWorld.z = 0;
Vector3 direction = mousePosInWorld - g.transform.position;
g.transform.right = direction;```
yes reference the thing you actually want to modify
thanks
Note this method will only work if you are using an Orthographic camera projection, which is the default in 2D.
That's the thing though - cardPrefab isnt added into the screen until after Start(), so I have to go into the cardPrefab (I think) to change it. Do I need to change HandPosition's prefab?
if you spawn it in code then set the reference to the newly made instance in code too!
make sense?
Its not going to work if you dont reference the instance and modify values on that instance is it?
Yep, that makes way more sense! Thanks. Yall are so helpful for my non coding brain 😭
Its important to understand instances. The prefab is the "template" that you make copies from.
Therefore you need to have a reference to the copy you want to change stuff on.
Will do! I defiently need to watch a ton more videos on things like this, lol.
There we go, it immediately worked. Thank you so so much!!!
any idea why it wont work?
Make sure the collission has the Enemy tag
Yeah they do
Make sure the method is called by logging a message
is ur game 3d
Add Debug.Log on the first line before the if statement to make sure it's even running
Make sure the objects both have a valid 3d collider
that is not a trigger
Also, read this: https://unity.huh.how/physics-messages
nvm i got it
Good job team
✅
f1 pitstop
can i make scenes into like levels or smth?
u could
nice
depending on ur game size i feel like scenes are maybe a bit overused
could have everything in 1 scene is also an option
Generally you use scenes when you need different baked lighting and static objects and occlusion culling
if not, just use prefabs
I would like for the ray to go toward the black triangle in the x axis and keep the y axis of the blue triangle. I have tried changing the second vector to a direction instead of a vector and i still got the same result. Also how does the distance work because if i make the distance 10f instead of 1f, a 10x increase, only doubles the length of the ray.
You are using DrawRay improperly
DrawRay takes a position and a direction
You are passing in two positions
If you want to pass in two positions, use DrawLine
Your raycast, similarly, is borked
you are passing in two positions
If you wish to pass into two positions, use Physics2D.LineCast instead
otherwise you must pass in a position and a direction
okay thank you i will try that
if i make the distance 10f instead of 1f, a 10x increase, only doubles the length of the ray
This is not true and simply related to:
- The hit point isn't always the full distance. The distance is just the max distance. It can hit objects before that
- Your improper use of DrawRay means you're not drawing things properly anyway
you also need to actually check if the raycast hit anything
e.g.
if (hit.collider != null) {
Debug.Log($"We hit {hit.collider}");
}
else {
Debug.Log("Didn't hit anything");
}```
i have the debug log hit or does it return something no matter what?
if the raycast didn't hit anything, all the data in hit will be empty basically
I don't undersdtand this question. Yes you are doing Debug.Log(hit) but that doesn't let your code differentiate if you actually hit anything or not.
the data inside the hit struct is going to be nonsense/garbage if it didn't actually hit anything
so it can't be used for drawing anything in that case
I found some figure eight code on the internet that works perfectly but my problem is I only want to do a single figure eight.. how do I know at what time this will have gone through a full cycle based on its speed? I did a test and 1 speed = around 12.57 seconds if that helps.....
transform.position = startPos + (Vector3.right * Mathf.Sin(time / 2 * speed) * xScale - Vector3.up * Mathf.Sin(time * speed) * yScale);```
Sin loops every two pi
since it's doing time / 2
this will be 4PI
i.e. ~12.56
so your estimate/test is roughly accurate
okay thanks, so then I just divide that by the speed and that should be the total duration for any speed
I would get rid of the / 2 which is arbitrary
It's necessary to make the figure eight. It needs to cycle twice as fast on one axis than the other.
I would do this:
float desiredDuration = 5; // i.e. 5 seconds
time += Time.deltaTime;
float theta = time * ((Mathf.PI * 4) / desiredDuration);
transform.position = startPos + (Vector3.right * Mathf.Sin(theta / 2) * xScale - Vector3.up * Mathf.Sin(theta) * yScale);```
oh I see
then you need 4pi
I believe my code snippet above will work and you can plug your desired duration into that first variable
It's just off the top of my head though so it's possible I erred
(I just changed ((Mathf.PI * 4) * desiredDuration) to ((Mathf.PI * 4) / desiredDuration) which I believe is correct)
is this how you load a scene?
SceneManager.LoadScene is a way to load a scene, sure.
it does not work for me tho :(
It's probably not running
or you have errors
As suggested above you should add Debug.log to this code to make sure it's actually running
both before and after the if statement
Yeah
did you add the scene to your scenes list in the settings
https://paste.mod.gg/rkdedqyspqkb/0
https://streamable.com/smlar3
I don't know if this error is scripting related, but i think it is.. I have no idea on how to fix this. (Meshes and objects changing size)
A tool for sharing your source code with the world!
thats scaling issues..
b/c the object becomes a child of an object.. the one that rotates..
if its scale isn't 1:1:1 when u do rotations its gonna skew and warp the child
the warning you see is unrelated to the gameplay stuff you're seeing, which is due to non-uniform scaling.
Is there a way to fix that?
get rid of non-uniform scaling in your hierarchy
rule of thumb: any object that has one or more children should not be scaled.
or at least - only scaled uniformly (same on all axes)
if u have objects that need scaling always keep them seperate..
- Main Object <-- this object would remain scaled 1:1:1
- Graphic <-- this object represents the actual object and would be the thing scaled
then if u grabbed "main object and rotated it around the graphic would follow along (w/o any weird skewing)
Hi Unity people, I am wondering something: Is it possible to display a wireframe cube that only contains 12 edges? There are cubes defined on Unity, but if you show them, there are more than 12 edges (there are bars in the diagonal of each side)
my intent is to display a 3D box around a person for AR applications. I can do that with the current cubes, though there are these annoying diagonal bars on all sides that make it hard to see through
They are already seperated, they arent the child of anything.
Issues with semisolid platforms
Use a LineRenderer, a specially desized mesh, or e.g. GL_Lines
are there some specially designed cube meshes that are already like this? I could use them from internet. Otherwise, with LineRenderer, how does it work? I can select the lines that I would render ?
how does it work? I can select the lines that I would render
You specify exactly which points the LineRenderer should trace yes
thanks
are there some specially designed cube meshes that are already like this
I dunno, I was thinking you'd make one. Note that all meshes use triangles so this would be like a mesh that's actually the "framework" so to speak
I am a little bit confused on linerenderers, how do I modify this? I can see the meshrenderer
MeshRenderer and LineRenderer are completely unrelated
ok
In the LineRenderer you add the points you want and it draws a line between them.
Oh, I see, so you have to completely draw the cube with each vertex defined as a 3D vector and define lines between them ?
ya soo u see the Positions
u can have as many as them as u need
can add them in the inspector.. or anytime during runtime with a reference to the line renderer
I see, thanks. Too bad that there is not something built in. I will probably work on this later as it is less easy than working with 3D objects
u can also use gizmo's if its something u need only while development
well you really only need to do it once and then make it a prefab
mousePos = Input.mousePosition;
root.style.left = mousePos.x;
root.style.top = (Screen.height - mousePos.y) - 100;
Debug.Log("x = " + mousePos.x + " y = " + (Screen.height - mousePos.y));
so basically how would i center UI to my mouse?
!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.
ok
mousePos = Input.mousePosition;
root.style.left = mousePos.x;
root.style.top = (Screen.height - mousePos.y) - 100;
Debug.Log("x = " + mousePos.x + " y = " + (Screen.height - mousePos.y));
so basically how would i center UI to my mouse?
This worked, but the lighting is just resetted and same for the post proccesing.
any idea?
"is just resetted"?
if the scene lighting looks wrong (notably, if surfaces facing away from the sun light are black), you probably need to generate lighting in the editor
Unity automatically creates ambient light data when you enter play mode
the server discouarges sending one-word messages with no content
oh
anyways how do i set code to use an object and change its color?
using UnityEngine;
public class Colortest
{
void Update()
{
if (Input.GetKeyDown(KeyCode.R))
Object<Renderer>().color = Color.red;
}
}
current code is this
There is no method named Object
well yes
perhaps you were looking for GetComponent
yea
but there is no getcomponent(or im blind)
Hello, does anybody know why OnCollision() mightn't be calling when my player collides w an another object?
ideally handle the component yourself instead of using get component in script most times if possible
many reasons, post code pls
there is a more pressing issue (:
you probably also wanted to create a component here -- so that you can attach it to a GameObject
alr: ```cs
private void OnCollisionEnter(Collision other)
{
Debug.Log("Collision!");
// Check if it is grounded
if (other.contacts[0].normal.y > 0.1f)
{
isGrounded = true;
velocity.y = 0f;
}
}
Note not even the collision log is called
Colortest doesn't inherit from anything. It's an ordinary C# class.
is it 2d or 3d? and do you have a rigidbody
so i input name of block?
3d and yes on the gameobject this script is attached to
I don't know what this would mean
i have a cube
The script does not care at all about what your objects are named
and im attempting to do what the tutorial said
The tutorial did not say to create a class that doesn't inherit from anything.
oh huh I can't make the rigidbody kinematic?
using System.Collections;
public class ExampleBehaviourScript : MonoBehaviour
{
void Update()
{
if (Input.GetKeyDown(KeyCode.R))
{
GetComponent<Renderer> ().material.color = Color.red;
}
if (Input.GetKeyDown(KeyCode.G))
{
GetComponent<Renderer>().material.color = Color.green;
}
if (Input.GetKeyDown(KeyCode.B))
{
GetComponent<Renderer>().material.color = Color.blue;
}
}
}
this is code
hold up
notice something here that your class does not have: a parent
private void FollowInUI(Vector3 mouseScreenPos)
{
Vector2 localPoint;
RectTransformUtility.ScreenPointToLocalPointInRectangle(uiElement.parent as RectTransform,mouseScreenPos,null,out localPoint);
uiElement.localPosition = localPoint;
}``` i use RectTransformUtils
that allowed the GetComponent
You'll need to actually attach the script to an object in the scene too
Importantly, this also means that your class is now defining a new kind of component
which you can attach to a GameObject
yay code threw no errors
thx
though i've done that
wow i really don't like ui toolkit
when scripting it
i think its pretty cool.. i use to use anchorPosition. for everything
then i figured out about that ScreenPointToLocalPointInRectangle 😄
what a mouthful
they're talking about UIToolkit here, not UGUI
ahh that must be the .style. stuff in here
i would not advise using the sludge generator if you don't yet know what a MonoBehaviour is
consider !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
dont believe so
you would need to handle collisions manually but think there are other options
i seen someone say to have a duplicate player that isnt kinematic for example
that's unfortunate, I think I'll manage w the non-kinematic. I'm only experimenting anyways
tysm for the help
its time to learn
bruh i gonna be waiting because of older version of essentials project
consider going to do that instead of coming back to say that multiple times lol
ive got an enemy AI that detects the player when in range and when the player is close enough it will attack the problem is cause there both trigger colliders how do i differentiate between them in code
each collider has its own gameobject no ? if not you cant
oh u mean have a empty child to my enemy for the attack radius
You'll need to put trigger colliders on their own objects, yeah
ok cool cool
And then put a component on each object that sends a message to the enemy component
tbh id use physics queries
like overlap and such
yeah ill just use a delegate
Hey, having some issues with a new error message I haven't figured out how to fix. I keep trying to figure out WHY dealerDeckManager is null, because it is, but I don't know when it's becoming null.
Script referencing it:
public GameObject dealerDeckManager;
public GameObject dealerHandManager;
public void Start()
{
dealerDeckManager = GameObject.FindWithTag("DealerDeckManager");
}
```I don't know, Ive tried to figure out why DealerDeckManager has been null for the last 30 minutes. Any ideas of why? (I do know that it is DealerDeckManager, not the script.) Thinking it has something to do with it being a prefab, but everytime I click the reference it tells me its the DealerDeckManager in the scene. @ me if you respond, thanks.
dealerDeckManager presumably isn't found with tag so its replaced by null?
also yeah maybe it is because you linked a scene object from prefab, if you spawn more that same reference wont be in the new prefab
prefabs cannot reference sceneobjects (unless they are in the same scene therefore is an instance not prefab)
Can you show the full error?
The bottom and left poart of it is cut off
you may need to scroll
Will do
or make that window larger
ok looks like this is happening when you click a button
can you show how you set up that button click handler?
And if you click the object in the bottom left here where does it take you?
public void CelestialBond()
{
//Swap hands with other player
DealerNewHandValue = handManager.handValue;
Debug.Log("DealerNewHandValue: "+ DealerNewHandValue + " PlayerHandValue: " + handManager.handValue);
BetManager.ResetCurrentHandCelestialBond();
Debug.Log("ResetHandCelestialBond");
Dealerhand.DealerCardValueChangeCelestialBond();
Debug.Log("DealerNewHand Value: " + DealerNewHandValue + " DealerHandValue " + Dealerhand.DealerhandValue);
}
Here - Connects to the error text on DealerCardValueChangeCelestialBond()
no i mean
I don't want to see the code I want to see the actual object it takes you to
Oh! Makes a little more sense
show where that object is and its inspector
Sure click on that and show its inspector
We're basically following the chain of references here
Yeah, its doing the dang prefab again. Ugh, unity some times! (It's not unity lol.) Thanks again, I know you've helped me a TON with this project
{
if(target != null && isWalking == true)
{
Debug.Log("moving");
Vector2 moveDir = target.position - transform.position;
rb.linearVelocity = speed * moveDir.normalized;
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.tag == "Player")
{
isWalking = true;
playerDetected = true;
target = collision.gameObject.transform;
anim.SetBool("IsWalking", true);
}
}
private void Attack()
{
isWalking = false;
Debug.Log("attacking");
}```
idk if im tweaking rn but when attacking debug gets called moving debug gets continously called still
which script is this? Is there more than one of them in the scene?
also you don't need isWalking == true
you can just write isWalking
just one in the scene
You sure? Search the hierarchy while the game is running with t: ScriptName
also show the rest of the code
{
public bool playerDetected = false;
public bool isWalking = false;
public Transform target;
public float speed = 5f;
public Rigidbody2D rb;
public Animator anim;
public AttackColliderAlert ACA;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
playerDetected = false;
}
private void OnEnable()
{
ACA.attack += Attack;
}
private void OnDisable()
{
ACA.attack -= Attack;
}
private void FixedUpdate()
{
if(target != null && isWalking == true)
{
Debug.Log("moving");
Vector2 moveDir = target.position - transform.position;
rb.linearVelocity = speed * moveDir.normalized;
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.tag == "Player")
{
isWalking = true;
playerDetected = true;
target = collision.gameObject.transform;
anim.SetBool("IsWalking", true);
}
}
private void Attack()
{
isWalking = false;
Debug.Log("attacking");
}
}```
ill do that now
t: TraitorAI
definitly just one
oh shit wait yeah
yeah its calling twice
once when it shod
and 2nd when the child collider hits it
Debug.Log($"Entered a trigger: {collision.name}");``` might be useful as the first line there
but surely it shouldnt be calling for a collider on a different gameobject even if it is a child
you will get a call for every collider it touches
and yes all of your child colliders are part of you
if you have a rigidbody
so then how do i use more than one trigger
cause i have a trigger collider on my main one for walking distance and a trigger on my child for attack distance
you would put a separate script on the child if you want to detect only the triggers for that child
ive done that yes for the attack one
ill try that
Not a code question
Do you have a recomendation for whichc hat this is suited for?
Thank you lots lad
Does anyone know how to set a sprite renderer to dynamically render a constantly shifting polygon collider? I know how to set a polygon collider to match a sprite but not the reverse, and google is only showing me sprite-to-collider answers because I dunno how to phrase it.
I would probably look into SpriteShape
Taking a look now, thanks!
or - depending on exactly what you're doing - this might be doable with a relatively simple shader
@wintry quarry I dunno shaders yet. I’m trying to color a polygon collider 2d with a flat color that lerps.
Would learning a shader for that be easier than the spriteshape thing?
Btw I know how to do it if I use a mesh, I’m trying to somehow skip generating a mesh from my points, specifically. I don’t even know if that’s possible.
hey there guys I'm a complete beginner and I am making flappy bird just to get in touch with the software. Whenever I generate a script for an object and I edit it and i write gameObject the list of items doesn't seem to appear. Idk what I'm doing wrong, I'd appreciate the help
!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
you need to configure your IDE^
Okay, I'll get to it
may want to grab this plug-in if u haven't yet as well
I managed to fix it, I'm getting informed on the basics now with tutorials and stuff, thanks guys
is there a way to check if ANY part of a trigger leaves another trigger? ie. green collider still touching red collider but does not fully overlap
you would need to e.g. place little "tester" colliders at the corners for example, or do your own OverlapPoint calls.
cheers
currently i'm trying to "clamp" my camera's movement if it goes to far away from it's origin, but because i'm working in a vr environment i can't just override the camera's position unless i'd like to rework unity's camera script for vr devices
would the best way to move an offset counter-acting the camera's movement if far away? or is there any better solution, been stuck on this for a couple hours so any help appreciated
I think I made a mistake
I'm trying to get them to spawn on the sides, with a specific height difference, but it ain't working
we're gonna have to see the code to help
First is the spawn code, second is the move code
I'm not exactly clear on what this means
and this whole unit thing seems overcomplex - why not just set these parameters in the inspector instead:
float lowestPoint = -1 * yOffset;
float highestPoint = yOffset;
float y = Random.Range(lowestPoint, highestPoint);
float x = -12;
summon(x, y);```
I want the red units to spawn on the top and go down, from the left side of the picture to the right side of the picture. I want this to happen to the three other sides too
create spawners at those positions
and have the spawner spawn them at its own position
rather than trying to hardcode numbers in your code
Does that mean I have to make 4 of the unit wall?
I don't know what "4 of the unit wall" means
You would make 4 spawners, sure
Or just one script that has references to a bunch of empty objects for the positions
A spawner is the prefab of the wall entity?
The spawner is the thing that spawns things
the prefab would be the thing being spawned
Can you place the spawner somewhere?
you can do whatever you want
So in the 4 areas, I'll just set the spawn location to different coordinates, then vary the height/width?
I don't understand what you mean by that exactly, sorry
I don't exactly know what a spawner is
a script/object whose job it is to spawn the monsters
spawn means to create
or instantiate
I did make a spawn script
I would just do something like this:
public class Spawner: MonoBehaviour {
// Assign all these fields in the inspector
public Transform PointA;
public Transform PointB;
public GameObject prefab;
void SpawnSomething() {
float random = UnityEngine.Random.value; // random number 0 to 1
Vector3 position = Vector3.Lerp(PointA.position, PointB.position, random);
Quaternion rotation = Quaternion.Slerp(PointA.rotation, PointB.rotation, random);
GameObject spawnedThing = Instantiate(prefab, position, rotation);
}
}```
then you can make empty objects for points A and B
and position them wherever you'd like
and reference them
and it will just work
(you'd add the timer stuff in Update and call SpawnSomething() when the time is right)
Spawn is a verb.
A spawner is a thing that does the spawning
So in my case I would have 4 points?
2 on each side
And those are just empty creates in Unity?
you create empty gameobjects so you can position them in the scene then set the references (drag n drop in pointa, pointb)
Asking a bit dumb question, but is the gameobject when it has the sprite render, or what is the gameobject?
no a gameobject is just that, exists without any other components but Transform & GameObject
Hello can anyone explain to me like you would to a toddler why my Debug.Log only executes once when I click on the same inventory slot over and over, I can send the full code if necessary:
InventoryUI.cs
private void OnSlotClicked(int slotIndex)
{
Transform slotTransform = slotContainer.transform.GetChild(slotIndex);
SlotUI clickedSlot = slotTransform.GetComponent<SlotUI>();
Debug.Log($"Clicked Slot: {clickedSlot}");
if (Inventory.Instance.SelectItem(slotIndex))
{
ShowSelection(slotTransform.position, slotIndex);
}
else
{
HideSelection();
}
}
private void ShowSelection(Vector3 position, int index)
{
itemSelection.transform.position = position;
itemSelection.gameObject.SetActive(true);
}
private void HideSelection()
{
itemSelection.gameObject.SetActive(false);
}
Inventory.cs
public bool SelectItem(int index)
{
if (index >= 0 && index < inventory.Count)
{
selectedItem = inventory[index].item;
OnInventoryChanged?.Invoke(this, new OnInventoryChangedEventArgs
{
itemChanged = selectedItem
});
return true;
}
DeselectItem();
return false;
}
public void DeselectItem()
{
selectedItem = null;
OnInventoryChanged?.Invoke(this, new OnInventoryChangedEventArgs
{
itemChanged = selectedItem
});
}
Are you sure it only executes once?
Maybe you just have "Collapse" turned on in your console?
I'm very sure yeh
i do yeh but it's only called 1 times
Oh the slots are buttons
private void Start()
{
for (int i = 0; i < slotContainer.transform.childCount; i++)
{
slots.Add(slotContainer.gameObject.transform.GetChild(i).GetComponent<SlotUI>());
Button button = slots[i].GetComponent<Button>();
if (button != null)
{
int index = i;
button.onClick.AddListener(() => OnSlotClicked(index));
}
}
Inventory.Instance.OnInventoryChanged += InventoryInstance_OnInventoryChanged;
RefreshUI();
}
I might have picked the wrong channel I'm not really a beginner but right now I feel super stupid
ok good work on not getting hit by the variable capture thing at least 😛
gotta capture the index
Do I have to make all 4 spawners into my Wall object?
but what's really going on here i'm so confused
Some simpler problems are easy to solve. You could create bounding boxes around the colliders and test if one is completely enclosed within the other.
You'd need to do this constantly, though, and it would be inaccurate in some cases
wdym "into your wall object" ?
I essentially have a "itemSelection" game object that lights up when I select an item in the inventory and what I'm trying to do is just make it disappear if I click an already selected item. i feel like I'm ovvvverrrr complicating this whole thing, it shouldn't be this hard
meant to reply here.
will look into this!!! i'm currently trying to essentially make a collider with code and i think i mostly have it figured out
Well my wall prefab is the thing I want to spawn, how do I get it to spawn at the spawners?
see https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Bounds.html (and the bounds properties of the colliders)
What does InventoryInstance_OnInventoryChanged do, if anything?
you link it as the prefab, then create a condition/ timer whener you want to run the spawn function
private void InventoryInstance_OnInventoryChanged(object sender, Inventory.OnInventoryChangedEventArgs e)
{
RefreshUI();
}
private void RefreshUI()
{
List<ItemSlot> inventoryItems = Inventory.Instance.GetInventory();
for (int i = 0; i < slots.Count; i++)
{
if (slots != null)
{
if (i < inventoryItems.Count)
{
slots[i].SetItem(inventoryItems[i].item, i);
}
else
{
slots[i].ClearSlot();
}
}
}
if (Inventory.Instance.selectedItem == null)
{
itemSelection.gameObject.SetActive(false);
}
}
Is the prefab also a GameObject then? Do I have to change its x and y coordinates to the specific spawner I'm using?
Seems like this is going to run every time you click anything basically, right?
itemSelection.gameObject.SetActive(false); < is this a problem?
Are you deactivating the object you want to be clicking on?
I'm not really sure which object is being clicked on and has which script
Lemme send a quick video
prefab is which object you are going to create/clone, this should be added from the Project view to the field on script. the xy is set during instantiation of a clone. Instantiate creates a clone of an object, yes GameObject but can be any type that dervies from UnityEngine.Object
is the red part like a second object that you're activating?
Maybe it's just blocking the raycasts
the red part is the itemSelection
Make sure raycast target is disabled on it if it's not supposed to block raycasts.
omfg
is there a global scale i can use? lossy scale is get only
A prefab is an asset that contains a GameObject. You can reference this asset as a GameObject or as any component type on the root object.
i go bury myself
literally
For example, if the prefab's root object has an Enemy component on it, you can reference the prefab as an Enemy, and instantiating the prefab will give you a reference to that Enemy component on the newly-created copy
spent HOURS on this
Oh boy!
thanks for the help I love you
lossyScale is named "lossy" for a reason -- your world scale depends on the rotation and scales of your parents
you've probably seen skewing when rotating an object whose parent is non-uniformly scaled before
If you know that your object's parents are all uniformly-scaled, you can calculate the appropriate local scale yourself
i keep all paretns at scale 1
just easier
Always keep scale at 1
was reading that non-uniform stuff can create problems for colliders as well
Hey! I was just wondering if there was any way to draw a Physics.OverlapCapsule for debugging like how a collider is drawn when editing? I'm in 3D, anyone got any tips? Thx
is it for debugging? there is a built way to see them in physics debugger now
Yes for debugging. Can you tell me how?
Window -> Analysis -> PhysicsDebugger -> Queries
found it tysm
Which basic games do you think are good to understand physics in programming
flabby birb
Nvm that dumb question
I'm making it but I think the made in components aren't helping me at all 😭
"the made in components" ?
wdym
Built in
Ye
You're not going to be making a game entirely out of built-in components
You're going to be using mostly custom components for everything
Ig that for the fall of the bird I used free fall equation, Idr much
I'll have to check it
I mean… Not necessarily.
falling can be done with a Rigidbody just fine
My rigidbody is set to kinematic iirc
Why?
free fall equation ?
are you following some tutorial ?
I was
acceleration due to gravity.
The famous gt
well yeah but if its a rigidbody why does it need it lol already does gravity for you
just read it was kinematic so ig it makes sense..no idea why it was kine
hello i am doing some experiments trying to make my own movement system without a character controller or rigidbody so I've implemented a collision system (using built-in physics though), but I think there's a logical error:
- It should "simulate" the player going to a position and check if theres a collision and if so, then do a binary search across the vector until there's no collision and calculate velocity from there
The issue is that I think it's simulating the player in the opposite direction (ie player is going to positive Z, it'll simulate negative Z). It might just be a + and - issue but I can't spot it. Can someone help?
Here's the MonoBehaviour: https://pastebin.com/JiMpnwLY
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Ig he wanted to write his own physics.
I'll try unsetting the kinematic behavior to see if it behaves like I want
That too
btw unrelated to your question, You shouldnt multiply mouseInputs with TIme.deltaTime
oops thx
I'm in game dev mostly because I want to practice some math and physics coding
nothing wrong with that I suppose
I'm at least having fun with it
go for it, just be aware the quirks of keinamtics
unity doesn't like things like OnCollisionEnter if the other object isn't a "dynamic" one etc.
I've always wanted to be gamedev and such
I want to someday build a gameengine for the fun of it
rust vibes
is there any way to draw like a debug point?
not a point but you can Draw a sphere gizmos or a box
check out the gizmos namespace https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Gizmos.html or use https://github.com/vertxxyz/Vertx.Debugging
alr thx
Hi!
Is there any room for improvement for the performance of SetTiles in 2D top-down tilemaps? I was planning to do my own using something like ECS but I still don't have a plan to render just one quad mesh per chunk (is it necessary for it to be per tile? I don't mind having a flat map if that allows me to see more of it at once) each with its own texture. Is that a possibility. I also plan to perform flood-fill algorithms frequently.
Maybe start with profiling your current setup and identifying the bottleneck. Assuming there's a performance issue at all
Yes I already did that and SetTilesBlock is the bottleneck
Can you share the profiling data that made you come to this conclusion?
Yes hang on
There's also the get chunk thing but I do have a few ideas to fix that. Even if it was 0, the other calls are still too much
Can you expand it further?
I mean expand the SetTilesBlock.
The fact that Self Ms is near 0, means that it's not the method itself, but something deeper the hierarchy.
Also, I have a feeling like it's the GC that is at fault here. You're allocating a lot of garbage.
Indeed, but you want to know what exactly in the method is being heavy. Even if it's an engine method.
Is that really that much? And how do I take that down?
Don't allocate temporary objects, like arrays/lists basically. Use pooling where possible or just cached objects.
Do you have custom tiles? Can you share their code?
No code for the tiles. I'm using the tilemap only as a renderer. The logic is run manually
Hmm... Do you have gameObjects assigned to tiles?
Also, is that in deep profiling mode?
Does the profiler help to pinpoint the function that is doing all of that?
Nope
This is my hierarchy, and those overlays are just quads. NearbyOverlays just has a transform
Yes
Sort of. You can see that there are 1280 calls to GetTileData
First of all what I'd try is profile a build(with and without deep profiling enabled) and see if the time of that call changes drastically.
Yes that is because the chunks are 16*16 so the GetTileData is called once per tile
Regarding GC, you should be able to see it in the graph breakdown by color. If you don't see it, it should be fine I think.
Lastly, it would help to see your code as well.
Switching GC changes nothing in the graph
I can't say for sure, but I think unity should be able to handle 1000 tiles assignment with this method relatively easy.
I didn't understand this
Without deep profiling it's not going to let me see the time of that particular call, right?
Depends. It should show the top of the engine calls at the very least.
Deep profiling can impact performance heavily as it injects timing queries into the code. Cases where there are hundreds of calls can have a huge impact.
public void DrawChunk(int chunkXPosition, int chunkYPosition)
{
Cell[,] chunk = abstractBoard.GetChunk(chunkXPosition, chunkYPosition);
Tile[] tiles = new Tile[chunkSize * chunkSize];
BoundsInt bounds = new(chunkSize * chunkXPosition, chunkSize * chunkYPosition, 0, chunkSize, chunkSize, 1);
for (int i = 0; i < chunkSize; i++)
{
for (int j = 0; j < chunkSize; j++)
{
tiles[chunkSize * j + i] = FindCellType(chunk[i, j]);
}
}
tilemap.SetTilesBlock(bounds, tiles);
}
private Tile FindCellType(Cell cell)
{
if (debugShowTileProbabilities)
{
return tileDebug;
}
if (cell.misplacedFlagWhileGameLost)
{
return tileMisplacedFlag;
}
else if (cell.flagged)
{
return tileFlag;
}
else if (cell.hidden)
{
return tileUnknown;
}
else if (cell.exploded)
{
return tileExploded;
}
else return FindRevealedCellType(cell);
}
private Tile FindRevealedCellType(Cell cell)
{
return cell.type switch
{
Cell.Type.Mine => tileMine,
Cell.Type.Safe => FindRevealedCellTypeNumber(cell),
_ => null,
};
}
private Tile FindRevealedCellTypeNumber(Cell cell)
{
return cell.adjacentMines switch
{
0 => tileEmpty,
1 => tileNum1,
2 => tileNum2,
3 => tileNum3,
4 => tileNum4,
5 => tileNum5,
6 => tileNum6,
7 => tileNum7,
8 => tileNum8,
_ => null,
};
}
First of all, I'd cache chunk and tiles, so that you don't need to allocate new arrays for them every update.
Caching them means having those in the main script and passing them as arguments?
Sorry you meant in the class right?
For example, yes. Basically new keyword is the bad thing here as it allocates a new array. I don't know about chunk though. Are you allocating an array on the other side?
Yes
public Cell[,] GetChunk(int chunkXPosition, int chunkYPosition)
{
Tuple<int, int> chunk = new(chunkXPosition, chunkYPosition);
if (!loadedChunks.ContainsKey(chunk))
{
ComputeChunk(chunkXPosition, chunkYPosition);
}
return loadedChunks[chunk].cells;
}
public void ComputeChunk(int chunkXPosition, int chunkYPosition)
{
Tuple<int, int> chunkPosition = new(chunkXPosition, chunkYPosition);
int[,] mines = ComputeMinesInChunk(chunkXPosition, chunkYPosition);
int[,] numbers = ComputeNumbers(mines);
Chunk chunk = new()
{
x = chunkXPosition,
y = chunkYPosition,
cells = new Cell[chunkSize, chunkSize]
};
for (int i = 0; i < chunkSize; i++)
{
for (int j = 0; j < chunkSize; j++)
{
chunk.cells[i, j] = GetCell(i, j, mines, numbers);
}
}
loadedChunks[chunkPosition] = chunk;
}
public int[,] ComputeMinesInChunk(int x, int y)
{
int[,] output = new int[chunkSize + 2, chunkSize + 2];
for (int i = -1; i < chunkSize + 1; i++)
{
for (int j = -1; j < chunkSize + 1; j++)
{
if (boardGenerator.IsMine(chunkSize * x + i, chunkSize * y + j))
{
output[i + 1, j + 1] = 1;
}
}
}
return output;
}
Compute numbers is just a convolution (it didn't let me fit it in)
Yeah, that's not great.
And what's even worse is it seems like you're doing it every frame?
Not every frame but 5 times per frame
Right I'll try that
Thanks
Declaring the arrays in the class instead
Right?
Basically you should use this signature instead
public void ComputeMinesInChunk(int[,] output)```
And just have one "buffer" array that you reuse
spawner script.. editor stuffs
thanks anyway
Need help with a Physics Dungeon Generation Algorithm
public class Spawner : MonoBehaviour
{
public GameObject smallFoodPrefab;
public GameObject mediumFoodPrefab;
public GameObject bigFoodPrefab;
public GameObject collectiblePrefab;
public PathCreator pathCreator;
public int numberOfFoodItems = 10;
public Transform parentTransform;
void Start()
{
SpawnFoodAlongPath();
}
void SpawnFoodAlongPath()
{
int smallFoodCount = 0;
int mediumFoodCount = 0;
for (int i = 0; i < numberOfFoodItems; i++)
{
float t = i / (float)(numberOfFoodItems - 1);
Vector3 position = pathCreator.path.GetPointAtTime(t, EndOfPathInstruction.Loop);
Quaternion rotation = pathCreator.path.GetRotation(t, EndOfPathInstruction.Loop);
rotation = Quaternion.Euler(0, rotation.eulerAngles.y, 0);
GameObject foodPrefab = null;
if (smallFoodCount < 2)
{
foodPrefab = smallFoodPrefab;
smallFoodCount++;
}
else if (mediumFoodCount < 2)
{
foodPrefab = mediumFoodPrefab;
mediumFoodCount++;
smallFoodCount = 0; // Reset small food count after spawning medium food
}
else
{
foodPrefab = bigFoodPrefab;
mediumFoodCount = 0; // Reset medium food count after spawning big food
}
GameObject foodInstance = Instantiate(foodPrefab, position, rotation, parentTransform);
}
// Spawn a collectible at the end of the track
Vector3 endPosition = pathCreator.path.GetPointAtTime(1.0f, EndOfPathInstruction.Stop);
Quaternion endRotation = pathCreator.path.GetRotation(1.0f, EndOfPathInstruction.Stop);
endRotation = Quaternion.Euler(0, endRotation.eulerAngles.y, 0);
Instantiate(collectiblePrefab, endPosition, endRotation, parentTransform);
}
```Could you please help me resolve the issue with the Z-axis rotation of my stars in Unity? Despite following the existing code, the stars are still rotating on the Z-axis, which I don't want. Any guidance would be greatly appreciated!
fixed it , it was an issue with the script not updating in unity.
whats the proper way of making variable affect another variable
i have ready list of 100 items, how should i make them bulk affect player stats
what does it mean for a variable to "affect another variable"
forloop..
listthing[i].variable * otherVariable
yeah but thats the thing i dont want to permanently overwrite them
just make use of all the items currently carried
well don't.. store a default list and modify a different one
theres probably better ways to do that im not sure
do i have to include every field in the item class and then make loop for each of them?
ya, i looked at my stats stuff and i use structs w/ default values and then create new ones in code to be the modified versions
but i think u can use Scriptable objects too..
like using ints on them would require huge block of data in them
item.add("katana", "20str");
item.add("glasses", "10int");
item.add("shield", "100hp/10def");```
or perhaps i could make interface for the stat which takes base stat + all the stats from present items
that will work for adding and substracting, what with multiplying and dividing though?
i cant store that in int
oh true.. use a scaling system lol
how do i enter parameters for functions in different order?
they have setup default parameters so they not requirement
ok i forgot i add through function not constructor so it didnt highlighted
If items that modify character stats are core functionality in your game, I'd make the items as separate objects with separate item class, that can have a list of Effects. The effects would be what adds to the character stats. Each time an item is equipped/unequipped or a temporary effect ends, just loop the relevant effects and +=/-= to the character stats
does anyone know why im gettin this error with this part of my 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.
sorry im trying to put my code
im kinda stupid lol
you probably want to compare either the magnitude of the vector or only one axis of it to an int since you cannot compare the entire vector2 to an int
// void inputManagement()
{
float moveX = Input.GetAxisRaw("Horizontal");
float moveY = Input.GetAxisRaw("Vertical");
moveDir = new Vector2(moveX, moveY).normalized;
if(moveDir != 0)
{
lastHorizontalVector = moveDir.x;
}
if(moveDir != 0)
{
lastVerticalVector = moveDir.y;
}
}
there we go
that took an unnecessary amount of time to figure out
you're comparing a vector to an int, do you want to check if it's magnitude is/isn't approximately 0?
yes
if (!Mathf.Approximately(moveDir.sqrMagnitude, 0))
you can use .magnitude if you'd like
I say approximately 0, because floating point equality is inherently a dangerous thing. 0.000001 is not 0, so using equality is generally something you should avoid with floats
just looked up what magnitude is, sorry i'm not tying to find that
my bad
i'm just trying to make it to where my player faces left and right when a/d + w is pressed
i think
im following a tutorial and im trying really hard to intake information but its kinda difficult lol
so you probably want to compare the individual axes of the vector2 rather than its magnitude. that would make more sense considering you have two separate if statements
look more closely at what the tutorial has
alr
although using Mathf.Approximately would be better than !=
In the screenshot you can see it used .x and .y in the two if statements, unlike your code above
ohhhhh
ok i fixed it
tysm lol
so i think i just need to pay attention better
im gonna rewatch that part and try and understand what the tutorial is saying when im done writing this script
Imo if you're not understanding something then you shouldn't be copying it. Obviously you don't need to deep dive and understand everything, but at the very least it the concept needs to make sense in relation to the code you write
i understand the general concept of it, this script flips the player when a or d is pressed with w or s, i'm just trying to intake what all the operators and keywords do so i can remember those for the future
i know that != means not equal to, i know how to make if statements, and i know how to make functions
im just trying to understand the littler parts
your original code asked:
(x, y) != 0
Which is the part you had to understand to reason what it should be doing instead
!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.
anyone know how to fix this? the slash only goes on one direction
private void Slash()
{
slashes[0].transform.position = slashPoint.position;
slashes[0].GetComponent<Projectile>().SetDirection(Mathf.Sign(transform.localScale.x));
cooldownTimer = 0;
}
this is the code that summons it
Are you sure, you are taking the correct transform as source?
nvm no, I was not
i was getting the transform component of the child object, not the parent's
ok sso new questiion, how do I get a component of another object to put in the code?
If it’s part of the same prefab you could just drop it into the scripts public variables in the editor, otherwise just the same way of .GetComponent
Its part of the same prefab, could you please explain how?
In the same way you drop in the slash point on the attack script in this video
Define a public variable in the relevant script, it then appears in the inspector when you click the object that has that script attached
You can then drag the object/component/whatever type you want as long as it matches the type you defined in the script into that slot in the inspector
Make a public reference in the script and drag and drop the object into it
Hey everyone, got a small problem with ParticleSystem, when I was writing scripts:
So it says 1st one is depricated, so it's not recommended to use. So I tried to use with main, but it keep asking me for variable.
Is it okay to stay with 1st option for now because adding stuff like var main and etc. Is kinda out of beginnerc course?
And how can I change the second option?
Just assign main to a variable and modify that instead of trying to modify it on one line
it worked, thanks yall
Looking on that screenshot,
using ParticleSystem ps means telling code that ps means ParticleSystem?
And we use var to identify that main is a variable?
Thanks in advance
Can u guys help me make it so when the enemy touches u, player loses 20 hp
This breaks all
the code aint workin
var is for lazy developers and shouldnt be used inside of tutorials
but I can understand where they're coming from since dealing with the particle system is arse
The type is ParticleSystem.MainModule that you're getting back from it, but the dev typing the tutorial didn't want to type out the type so var is a shortcut. Basically you're saying hey compiler figure out the type for me thanks
The C# convention is to use var when the type can be inferred from what's being assigned, so even in that context it has a place
If I were to make an upgrade system for something like a rogue like after you beat a level, should I seperate the gameplay and upgrade scene into two different scenes in unity or would it be better to just keep it all on one scene?
But here it's not inferred so specify away!
Scenes just act as quick ways to bulk unload/load content. You can do it by destroying and instancing objects plainly too
Whatever works for you, basically
Which would be more simple for a beginner?
A persistent management scene would enforce certain things that would avoid basic referencing mistakes in the short term
Neither is easier ultimately
I'll just try to use a different scene then
If you're doing a level by level design it probably be easier to do multiple scenes
just because of the ability to deload everything
Otherwise you're making some management system that's to handle destroying each and one of those objects
I'm planning on making generated levels
then just replaying it with different enemies
and backgrounds etc
when i get to the art side of it
currently I'm just trying to plan out the upgrade scene itself
so for the code
i originally referenced the 2 game objects and tried to enable and disable them through the event system in the XR event thing but couldn’t get anything to work, this is what chatgpt gave me :
using UnityEngine;
using UnityEngine.XR.Interaction.Toolkit;
public class OpenCloseTest : MonoBehaviour
{
public GameObject closedBook; // Closed book model
public GameObject openBook; // Open book model
private XRGrabInteractable grabInteractable;
private bool isOpen = false; // Tracks the state of the book (open or closed)
private void Start()
{
grabInteractable = GetComponent<XRGrabInteractable>();
// Ensure the models are set correctly at the start
closedBook.SetActive(true);
openBook.SetActive(false);
}
private void Update()
{
// Check if the trigger is pressed (while holding the object)
if (grabInteractable.isSelected)
{
if (Input.GetButtonDown("Fire1")) // Change "Fire1" to the relevant input for the trigger
{
// Toggle the models based on the trigger press
isOpen = !isOpen;
// Enable/Disable models based on the current state
closedBook.SetActive(!isOpen); // If the book is open, close it
openBook.SetActive(isOpen); // If the book is closed, open it
}
}
}
}
this,
!code. Use a paste site
📃 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.
using UnityEngine.XR.Interaction.Toolkit;
public class OpenCloseTest : MonoBehaviour
{
public GameObject closedBook; // Closed book model
public GameObject openBook; // Open book model
private XRGrabInteractable grabInteractable;
private bool isOpen = false; // Tracks the state of the book (open or closed)
private void Start()
{
grabInteractable = GetComponent<XRGrabInteractable>();
// Ensure the models are set correctly at the start
closedBook.SetActive(true);
openBook.SetActive(false);
}
private void Update()
{
// Check if the trigger is pressed (while holding the object)
if (grabInteractable.isSelected)
{
if (Input.GetButtonDown("Fire1")) // Change "Fire1" to the relevant input for the trigger
{
// Toggle the models based on the trigger press
isOpen = !isOpen;
// Enable/Disable models based on the current state
closedBook.SetActive(!isOpen); // If the book is open, close it
openBook.SetActive(isOpen); // If the book is closed, open it
}
}
}
}
this is the code
i tried the OnTrigger function too and no result
this is my alt btw
As a general rule we do not help with AI generated code. But that looks ok, try adding some debugging to see what is happening
debugging to check if the trigger buttons work or wdym
btw, your alt needs to know what a 'use a paste site' means
then you should be paying more attention not less
also post a screenshot of your hierarchy for the book and the inspector of this script on the object
bet one sec
Then learn to write it yourself instead of relying on ChatGPT to do it
Why would we help you when you have no clue how to write code? We're not going to spoonfeed your whole game
no i tried that first but didn’t end up w a good result
there is your problem.
I told you to use the following
Book
Book Closed
Book Open
Then share what you tried. People are more likely to help somebody who actually put effort into it
ohhh so the “book” should be the parent of the 2 children (open) and (close)
yes
thanks i’ll try that
the script should go onto the main parent too, lemme fix all this
should both books have their own hit boxes, XR grab scrips or should the open book only have that since it’ll be the base
all the stuff you need should be on Book. Book Open and Book Closed should just be the models
just shows you how bad GPT is. This
public GameObject closedBook; // Closed book model
public GameObject openBook; // Open book model
private XRGrabInteractable grabInteractable;
makes no sense. why are 2 public and 1 private?
Yeah i think i’ll write the code myself from now on, chapgpt never really got me anywhere and i don’t think it’ll ever get my anywhere
good plan
yup
i should’ve taken more consideration w my original work too, i’ll start from scratch to refresh everything, thank you Steve and FusedQyou for the help
it marked them like that because 2 first are supposed to be assigned from inspector, and the 3rd is assigned in Start so its not exposed as public
Its a tool, use it wise, dont rely on it
noted
Feel free to make an attempt and share it in here. People are happy to help
will do
all 3 should be private serialized properties and assigned in the inspector
just a quick question, when accessing the trigger buttons for my controller, should i use an Ontrigger function or should i rely on the XR interaction’s event system thing
cuz those r the 2 ways i see it working but idk which is more reliable
OnTrigger has nothing to do with your controller
oh alright
wait so how i see this is if it weren’t in VR and if i wanted to press a specific key for this to happen, it’d work like:
OnMouseDown()
closedBook.gameObject.Setactive(false)
and i’d do the same for the open but but set it to true
in vr i have to specify when it’s being grabbed, and i have to access the controller’s trigger, so im assuming thats the “Activated” event
i’m slowly figuring this out hold up
Hi
I'm trying to make these specific tiles act both as a Ground and Wall because I have specific animations for each state
private bool IsGrounded()
{
RaycastHit2D raycastHit = Physics2D.BoxCast(boxCollider.bounds.center, boxCollider.bounds.size, 0, Vector2.down, 0.1f, groundLayer);
return raycastHit.collider != null;
}
private bool OnWall()
{
RaycastHit2D raycastHit = Physics2D.BoxCast(boxCollider.bounds.center, boxCollider.bounds.size, 0, new Vector2(transform.localScale.x, 0), 0.1f, wallLayer);
return raycastHit.collider != null;
}
these are the codes I use to determine if its Grounded or Wall
Anyone know how I might be able to ndo that?
Hey, I have this code: ```cs
Vector3 pointA = transform.position + givenVelocity;
but the issue with it is that pointA is calculated w givenVelocity in global space, but I really want to get the same output as `transform.Translate(givenVelocity)`
without moving the transform. Anyone know how?
Basically you want to know the velocity relative to the other transform?
https://paste.mod.gg/icpxstncilmx/0 why doesnt it update and just 1 debug message
A tool for sharing your source code with the world!
You might want something like
transform.InverseTransformDirection(source);
screenshot your complete console window
okay give me a min to boot thing up
Do you only have this script on one game object in your scene?
Cause it will debug for each one
A tool for sharing your source code with the world!
i have it on my player object
why share the same code again?
Some more detail would be useful. Can you share console logs + screenshots of your hierarchy
wdym? its a laptop
what do u mean? or what does it mean... im new
look at your screen, it's in pause mode
it wont do anything if it's paused
nvm
yea lol ur paused 2x
Did you put it back in play?
ye
Sick, still getting the problem?
ty
no, i just stupid cuz i have it paused... maybe a new tint would be good
It's ok it happens. I get tripped up by unity UI all the time too
1 question, what is that error... so i can ask in a certain channel
is it Unity related? or URP and Post-processing
Thsts an internal Unity error, difficult to say where from without a stack trace
so i should ask in #💻┃unity-talk ... ok
select the error and show the stack trace here
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)```
that is not the stack trace
what is stack trace
the bit that appears at the bottom of the console window when you select an error
thats it
ok, so it says PostFX so it's going to be PostProcessing releated
u cant scroll down there? just curious
thats all the error
what are the links to send for help again
wdym
never disappears
he meant !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.
is there a way to send longer videos here
try streamable, but that also limits you to 250 mb
and it supposed to rotate my object by the set amounts
make sure to check the rules before posting
please say it in one message lol
ok
type in full sentences if you expect help
why have I never used .Rotate
idk
I want to figure out why my play button doesn't fire the Play function when it is clicked. The other functions inside GameManager works fine, I've tested them, but the Play isn't getting called. I wonder if there is some set up I'm missing?
Code for GameManager: https://paste.mod.gg/rexamkmigdcd/0
A tool for sharing your source code with the world!
It be like that sometimes
When I use the code, instead of setting the rotation to the set values, it changes the value of several axes which is not what I want
You have it on a 3d GameObject with a sprite renderer instead of a UI GameObject on a canvas . . .
the transform values initially, and then with each of the 3 options
All I want to do is for it to set the X rotation to 0, 90 and 180 for each option
Re-asking cuz it got burried lol
I think you just need to set the rotation directly
With localRotation = for example
._.) I'll throw myself to the sea. thx
yeah i think so too
i dont really know about .Rotate but i did some research and it seemed funky
And then quaternion.euler? tried, same results
i think its doing world space maybe
Yeah exactly
Tie a string around you to pull yourself back out . . .
Can I see how you did that? I think that's how it should be done.
ok it may be doing global, but then why does it change 2 axes when I clearly only change one of the axes? it goes like 0 0 0 to 0 0 90 and then suddenly 180 0 180 or smth
Hold on I will do it
why not call both functions i dont get it
No idea, I've only ever done this by the Euler angles
same
This looks correct. For case 1, log the localRotation before and after calling Rotate to see if the value changed correctly . . .
Also, you don't need to call Rotate for case 0 since it's not rotating at all . . .
it was not intially 0, changed it to that for debugging
@cosmic daggerthese are the values
what do you mean by call both functions?
Are they the same values when logged? I ask because the values shown by the inspector don't always reflect the actual values of the object’s rotation . . .
were u rotating wrong axis
had a 90 degree rotation on the z axis which I was setting to 0 every time
Because I wanted to rotate along the X axis
I forgot I am zero-ing the Z axis too
idk maybe im just misunderstanding
hey i just started coding in unity yesterday and im following a guide on the basics where im making flappy bird, but i have no idea how to make the pipes move faster because right now they are slow as hell and changing the moveSpeed variable(even changing it to 50) doesnt do anything to speed it up. theres also no mention of speed in the pipe spawner. can someone help please?
So I'm trying to use a gamepad in my game all works fine besides the roatation, my player wont rotate at all when I use the right stick which I set as the action for looking for gamepads in the PlayerInput thingy.
post the tutorial and link to the pipe part and post your code please?
this is the video: https://www.youtube.com/watch?v=XtQMytORBmM
this is my pipe move script: https://pastebin.com/wgKPLwkR
this is my pipe spawner script: https://pastebin.com/MfeBhf10
🔴 Get bonus content by supporting Game Maker’s Toolkit - https://gamemakerstoolkit.com/support/ 🔴
Unity is an amazingly powerful game engine - but it can be hard to learn. Especially if you find tutorials hard to follow and prefer to learn by doing. If that sounds like you then this tutorial will get you acquainted with the basics - and then gi...
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
ah think i got it
transform.position = transform.position + (Vector3.left * moveSpeed) * Time.deltaTime;
or maybe not
Where did you change the move speed? In code or the inspector?
code
try: transform.position += (Vector3.left * moveSpeed) * Time.deltaTime;
maybe thats the same thing
but it helps me brain
im also kinda confused cause pipe move isnt a game object in unity and i cant find it in pipe spawner or anything
so idk what its actually doing rn
Make sure to change the inspector values as the code were only the default values. The speed for instances do not change if they're created as prefabs or added to the scene already.
are pipes a prefab and the pipemove script is on the prefab?
oh yeahh
pipe move is on the pipe prefavv
yep ty theyre faster when i change in unity
change public float moveSpeed = 7; to public float moveSpeed;
just cause y have it in code if u want to change in unity u know
ok tyty
id also suggest learning to write like this instead of whatever that line was
because that way you don't need to go through your math and make sure ur doing PEMDAS correctly
glad its working though
You should actually multiply the floats together rather than each with the vector 3
yeah also do you need to save the script every time for unity to recognise it because every time i save it takes like 10 seconds to get ready then another 10 to actually run the game when i press run
yes
ahk
wdym
yea i saw that
A vector has 3 floats so each would do three times as computation and probably take up a bit more memory on the stack temporarily
gotchu
Anyone able to help
Is the look action value correct and the expected value? Is the value really the mouse position on screen?
Uh not sure how it works with the gamepad what it returns
Like if its the position on screen or what
Why would you feed it to the camera function for converting from screen to world point then? Log it if you aren't sure.
If it's some normalized value.. then it's definitely incorrect
It needs to be the pointer position from screen space if you're to use the camera conversion function
How can I get VehicleUI Class variables to show as a sub-dropdown in my Array, similar to PlayerSlot?
[System.Serializable]
private class PlayerSlot
{
[System.Serializable]
private class VehicleLobbyUI : MonoBehaviour
{
[SerializeField] private TextMeshProUGUI vehicleName;
[SerializeField] private TextMeshProUGUI vehicleType;
[SerializeField] private Image firepowerImage;
[SerializeField] private Image mobilityImage;
[SerializeField] private Image defenceImage;
[SerializeField] private Image VehicleImage;
}
[SerializeField] private GameObject parent;
[SerializeField] private TextMeshProUGUI playerNameTitle;
[SerializeField] private GameObject readyGameObject;
[SerializeField] private VehicleLobbyUI vehicleUI;
public bool IsFree() => !parent.activeInHierarchy;
public void Show(string playerName)
{
playerNameTitle.text = playerName;
parent.SetActive(true);
}
public void Hide()
{
playerNameTitle.text = string.Empty;
parent.SetActive(false);
}
public void SetReady(bool isReady) => readyGameObject.SetActive(isReady);
}
I can't - It's a class of different objects. I assume it can't show nested class 😦
Is vehicle ui some sort of struct or non component object?
oh wait right it's not being instantied
what
ohh
you have it as a nested monobehaviour
remove that
er, but you have mono components on it ah nm it's just assets
hello i'm a beginner in object-oriented programming and i tried to made an enemy class, i wanna know how to make for made an object in my monobehavior class i try to do like this Enemy trainingDummy = gameObject.AddComponent<Enemy>(); and if i do the "basic method" like Enemy trainingDummy = new enemy(); that put me an error help
If you want to spawn things in at runtime you should be using prefabs and Instantiate
This has nothing to do with object oriented programming really, it's a Unity thing
i dont want i juste want my dummy use the method and anything in my class enemy
That doesn't make sense
You need an object to call methods on
Does the dummy already have the Enemy component on it?
yes and i try to make an object called trainingDummy
enemy is a class
is Enemy a MonoBehaviour?
remove monobehaviour from enemy, then you can do "new enemy"
time to learn coding using learn.unity
but i use monobehavior thing if i remove it nothing work anymore
please stop spamming that
anything that's a MonoBehaviour is managed by unity, so you shouldn't use new with it
you should instead tell unity to make it for you, with Instantiate or AddComponent
so i need to instanciate my dummy but how i make it an object of enemy ?
he has hp and method
you can't make Enemy on its own
it's a component, it needs to live on a gameobject
oh, sorry
you might want to make a prefab (or multiple prefabs, for multiple kinds of enemies) that has Enemy and then Instantiate that prefab
yes i put the script enemy on my gameobject training dummy
Hi! I'm messing with the Vector methods. This is my script that is responsible for rotating both my player on (y) and my player camera child object on (x). The angle datas I get from here.
My player turns to lookTarget just fine but my camera is turning up and away from the target. What am I doing wrong here?
sry if im lost first time i trying to do something like this and im french so i dont have the best english xd
why were you trying to instantiate a new enemy then? if it already exists
@fossil tree what exactly are you trying to do?
are you trying to create a new kind of enemy?
i dont want to instantiate it i wana make it an object of enemy
just make my gameobject script can be an object of enemy class
i honestly have no idea what you mean by that
what do you mean by "gameobject script", or "object of enemy"?
can you show your code maybe so we can see what you're trying to do?
seems like you're confusing quite a few ideas here
Care to explain what you think the difference between those is?