#💻┃code-beginner
1 messages · Page 134 of 1
It's offcenter
It's centered according to the object. You'd like to rotate it around the red cross here?
The red cross is off-center
Yes
Hello guys how do i import packages like Quaternion because it seems like my code aren't compiling
what the hell does that mean
So how do I adjust the cross location?
make your sprite image a child of the gameobject that handles your rotation stuff
then just move the sprite image
so its centred around where you want to rotate it
im quite perplexed, it won't highlight the words "Quaternion" "Euler" the frenchisity, but like if i had a package perhaps
anyone know of any kind of guide that shows off making a mobile input joystick without the new system? Just tried to implement it but it wasn't working out right, but I can't find any that cover the old input system
So I need a new game object?
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
Do these automagically obtain packages?
The packages are there
Yeah, drag another copy of your sprite without any logic, just the image, make it a child of the logic one
then just move the image
and delete the spriterenderer off the logic object
The packages are there, Unity isn't configured to generate the project files required for Visual Studio to detect them
Once that is done, it should be fixed
Oh i see
and to fix the inverted rotation transform.eulerAngles = new(0f, 0f, transform.eulerAngles.z - (Input.GetAxis("Horizontal") * speed2 * Time.deltaTime * -10));
why does unity make clockwise rotation decreasing angle
Weird
how to rotate an object around the origin, as in co ordinates (0, 0, 0)?
Jeez, it's still doing the same lmao
transform.RotateAround
ah ok
thanks
have you moved the image object so its centred where you want it to rotate
If you have a GameObject with a bool value of false, how do you set to true by simply adding an additional component? I can't seem to get it to work and I'm sure it's extremely simple.
Make sure the script is on the correct object. It should be on the object that is considered as "the center of rotation"
I had to move it over a bit
how do you have a gameobject with a bool value
your hierarchy should be
- Logic Object
- player rotation script
- image object
via a script containing several variables attached to that object
so a script with a bool value
uh theres probably an event for that
there is not, infact, an event for that
is there a reason you cant just getcomponent into your container and set the value?
had to move the object which seems kinda odd
why you got a circle
thats the new hidden object
only inexperience 😛 mind sharing what that would look like?
yeah, what i dont understand is why i had to move it to get the proper rotation
youre basically offsetting the image so that when the logic rotates the image does too, but it rotates with offset
So is my code having an error or is this a common thing?
GetComponent<Foo>().Bar = true; your implementations may vary
its not an error with code
if you fix it somewhere its either in editor or in photoshop
this is fixing it in editor
Alr, it just seems weird that the circle wouldn't go on the sprites center
Er wait, wouldn't go in the spot where the rotation should occur
That's why you put the sprite as the child of an object, and offset the child so the desired point is at the center of the parent
Then rotate the parent
Thanks for the help though
I think that's how it is now right?
Or no?
Maybe? Your screenshots don't show the Transform arrows of the parent object, so can't say
Yep looks good, if you want it to rotate around that white circle
Hi, I'm creating a very basic brick breaker clone. I have just implemented a little powerup system.
It works but I basically want some feedback on my solution and if I overcomplicated things.
So I have this base abstract class:
public abstract class Powerup : MonoBehaviour
{
public float duration;
protected Transform paddle;
public abstract event Action PickedUp;
public abstract IEnumerator OnPickup();
}
The only powerup I have a class that inherits this Powerup class - it has this event in it:
void OnCollisionEnter2D(Collision2D collisionInfo)
{
if (collisionInfo.gameObject.tag == "Player")
{
// Pickup stuff , make paddle wider etc.
StartCoroutine(OnPickup());
PickedUp?.Invoke();
}
}
The idea is to subscribe it in the game manager and add some score etc.
Is this a good way or how would you have done it? Am I overusing this observer pattern? Is a base class even necessarry? Other thoughts?
it rotates around the guys head for some reason
which is intentional, but i dont understand the need for the offset
Offset is there so you can, well, offset the center of rotation. Taking the center of the gray circle (a hat?) on your player, it would rotate like the red circle:
The center of the hat would stay along the red circle as you rotate. If that's not the case, the script that rotates is on the wrong object
do you guys plan out your mini practice projects?
or do u just start coding random stuff trying to establish game mechanics
cuz i feel like every time i want to practice something, like player movement and ui, and continue to add on, i begin to require a plan so everything works together smoothly and nothing gets too convoluted
Is that just the case of practicing anything for game dev?
I apologize for spam of quesitons
it depends if you have experience with how you should structure your code
if you dont have that much experience it might make more sense to plan it out because otherwise it might get overcompicated
wdym by that, just in general understanding the concept of writing clean code? (I thought that requires planning out the program too)
oh wait
structure is different than clean
i assumed they'd be similar
How do you develop that sort of experience?
just in general just plan your code out and then overtime you develop that habit?
ability?
skill? idk what youd call it
doing a bunch of different projects over the years, doesnt even have to be gamedev
oh i c
well i havent done that
so ig i have to plan my stuff out
thats annoying 😦
youll begin to notice patterns that make sense to do when you face certain problems
oh i see
thanks for your input
cuz i at first felt like i was going about it the wrong way
but i can see that it takes time
but if you are more of a beginner it makes more sense to plan it out so you avoid these overcomplications
clean code refers to code that is well-structured, easy to read, and maintainable
Any idea why the camera is not rotating to the NPC?
[SerializeField] private Transform _TransformPlayerCamera;
[SerializeField] private Transform target_LucyHead; // The object whose rotation we want to match.
private float speed = 3f;
private void FixedUpdate()
{
if (LucyHadHitPlayer)
{
Vector3 direction = target_LucyHead.position - target_LucyHead.transform.position;
Quaternion rotation = Quaternion.LookRotation(direction);
_TransformPlayerCamera.transform.rotation = Quaternion.Lerp(_TransformPlayerCamera.transform.rotation, rotation, speed * Time.deltaTime);
}
}
The Camera from the player should rotate to the head of the NPC if LucyHadHitPlayer.
Its not working, but it does reach this if statement, I checked it earlier with a print.
how can i detect collision setting a value if object 1 is on object 2 and a different value when the objects are no longer touching
Use OnCollisionEnter and OnCollisonExit
where is the code question?
well it's related to unity settings, where could I ask about that?
prob #📱┃mobile
aight yeah that looks to be a better place to ask
like this?
``void OnCollisionEnter2D(Collision2D otherObject)
{
}
``
Well otherObject is not a good name for the collision variable, but if you're using 2D physics yes that's the correct method signature for OnCollisionEnter2D
Collision2D otherObject isnt this just any object with a 2d rigidbody?
no it's a Collision2D struct
it's an object that describes the whole collision
is it possible to make a custom attribute that works like ContextMenu, but automatically adds a button?
Adds a button to what?
to execute it
[Button("my method name")]
private void namethatdoesntmatter()
{
Debug.Log("Button Pressed!");
}```
Yes using e.g. NaughtyAttributes for example:
https://dbrizov.github.io/na-docs/attributes/drawer_attributes/button.html
hey
void OnCollisionEnter2D(Collision2D GameObject CirclePrefab) is this more apropriate?
Im trying to find people that are doing projects i can help with/team up with, do you guys know of any good places or such to find that
!collab
We do not accept job or collab posts on discord.
Please use the forums:
• Commercial Job Seeking
• Commercial Job Offering
• Non Commercial Collaboration
👍
naughty attributes is cool 🥹
arrays arent meant to be resized
that why i make new one
but if you insist, just make a new array
but custom type messes up copying from one to another
how
Error CS0121 The call is ambiguous between the following methods or properties: 'MemoryExtensions.CopyTo<T>(T[], Span<T>)' and 'MemoryExtensions.CopyTo<T>(T[], Memory<T>)
please show what code you did as well
Looks like it's not sure if your second parameter is a Span or a Memory
shouldn't you be using Array.CopyTo? 🤔
or if desperate, just loop
i did
cant be specified?
this
im spamming a lot of values into the game
As mentioned before you should be using this https://learn.microsoft.com/en-us/dotnet/api/system.array.copy?view=net-8.0
then you are not using Array.CopyTo you are using MemoryExtensions.CopyTo
https://learn.microsoft.com/en-us/dotnet/api/system.array.copyto?view=netframework-4.8.1
probably have the wrong using directive or something
ah that sounded almost same
Where is problem?
IEnumerator PlayAnimation()
{
if (monsterSprites == null || monsterSprites.Length == 0 || monsterImage == null)
{
yield break;
}
while (true)
{
if (monsterImage != null) // Sprawdzamy, czy obiekt Image nadal istnieje
{
currentFrame = (currentFrame + 1) % monsterSprites.Length;
monsterImage.sprite = monsterSprites[currentFrame];
}
yield return new WaitForSeconds(0.1f);
}
}
You forgot using System.Collections;
Look at the line it says and see what's underlined in red
can u write me full script?
no
I wrote you the line you need
You can write your own script
also in the future share code here like this: !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
i ahve this
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
Right and like I said: #💻┃code-beginner message
is this a bad warning or a neutral waringnng?
if its not made by you neutral
not made by me
do you always get this warning or did it just appear?
just appeared
you can probably restart and it should go away
already did
Alr, I got my bullet to recognize that it's colliding with other objects, but how to I have it check to see if it's colliding with a specific game object?
you probably want to check the object it's colliding with for a tag or a component.
You probably don't want to actually check for a specific object, just one that has a specific tag or component on it
Alr, tag it is
is there a way to increase Debug.DrawRay's brightness/size
I think I have some old code that checks tags
on high res monitors it is barely percievable
brightness you can change by just picking a brighter color
it's always 1px wide afaik
Create a tag in that gameObject, is the bullet collidwr trigger?
`` void OnCollisionEnter2D(Collision2D otherObject)
{
string otherTag = gameObject.tag;
if (otherTag.Equals("player"))
{
// if we have touched the npc
if (otherObject.gameObject.CompareTag("shopkeep"))
{
Debug.Log("Collision Detected");
// show collision in debog log and destroy colided object
}
}
}``
if(other.gameobject.Comparetag("tag")){}
Wpuld be something like that
something like this or does my player tag even matter?
Just the other object tag that you want to check
So your bullet is not trigger right?
not currently
If not thats all there is to it
If it is instead of OnCollisionEnter2D()
It needs to be OnTriggerEnter2D(Collider2D other)
technically, this code is for player interaction with an npc
Works the same way
OnCollisionExit2D(Collision2D otherObject)
er how do i use oncollisionexit ig
Same way
ill try it, thanks
I'm very unfamiliar with unity and c#, but I'm trying to make a script that reads the last mouse location after a click. I don't think the script is doing anything though.
In the code here, I'm trying to change the color of a sphere (just so I can see things visually). The sphere is staying it's default color, so I can't if the script is running. I made sure to add it in the execution order.
https://hastebin.com/share/ofujujixug.csharp
P.S. The end is supposed to set the sphere back to it's original color, and just to make sure I know how to read mouse input.
Also thinking back (0,0) is probably one of the corners, but shouldn't a material change still happen?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I want to be able to tell which quadrant of a phone screen a click/tap occurred basically.
im pretty new to all this stuff but, what difrence between the tutorial (light) and my code (dark) is causing unity to say "all complier errors have to be fixed before entering playmode"
mouse position is in screen space. Top left of the screen is 0/0. Bottom right is Screen.width/Screen.height.
so checking positive or negative won't get you a quadrant
You need to configure your !ide so errors are underlined and you have autocomplete
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
Basic spelling mistakes should not be possible
You should be looking in the console window in Unity as well as getting your IDE configured. Both the console window and your configured IDE will tell you your errors. (also your filename/class is not capitalized like in the tutorial)
well shoot, its not detecting them
``void OnCollisionEnter2D(Collision2D otherObject)
{
// if we have touched the npc
if (otherObject.gameObject.CompareTag("shopkeep"))
{
Debug.Log("Hi NPC");
// show collision in debog log and destroy colided object
}
}``
did i mess something up?
oh wait duh...
Check whether the collision occurs at all
i didnt add the tag
and please use 3 backticks and cs: ```cs to create a codeblock that's highlighted
nope, still broke
will do
how do i check that?
just removing tag checker?
Log outside of the tag check
If it's not colliding at all, go through this resource: https://unity.huh.how/physics-messages
they arent colliding it seems
well im doing something wrong lol bc none of the steps fixed my issue...
Imma review my code again...
did you put a rigidbody
and check the graph on the page?
GameObject num1select = clickedObjects[0];
GameObject num2select = clickedObjects[1];
RaycastHit2D up = Physics2D.Raycast(num1select.transform.position, Vector2.up, 3);
RaycastHit2D down = Physics2D.Raycast(num1select.transform.position, Vector2.down,3);
RaycastHit2D left = Physics2D.Raycast(num1select.transform.position, Vector2.left,3);
RaycastHit2D right = Physics2D.Raycast(num1select.transform.position, Vector2.right,3);
if(up.collider.transform.position == num2select.transform.position || right.collider.transform.position == num2select.transform.position ||
down.collider.transform.position == num2select.transform.position || left.collider.transform.position == num2select.transform.position)
{
Debug.Log("Detected!");
}
so my goal is to detect whether or not an object is right next to the selected object
num1select = the first selected object
num2select = the second
the objects are being grabbed fine, but the raycasts don't seem to be working
Yes and yes lol
show both objects involved in the collision
what do you mean that the raycasts don't seem to be working? have you used breakpoints or logs to see what (if anything) is being hit by them?
yes it should log Detected to the console
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
again, have you used breakpoints or logs to see what is being hit?
because your log will only print if all 4 hit something and they are all in the same position as whatever those other objects are
how can I make a function onexit with raycast? I know that I can make if it hits with just if hit.gameobject but can I make an exit with that?
isn't || the or operator?
print what was hit. stop making assumptions about what you think your code is doing
So I'm trying to use the Pen pressure from a Wacom to draw however it does not want to work as intended... here's a snippet of the code. Any thoughts as to a fix?
https://gdl.space/ujeyunozek.cs
you'd have to store what is hit by the cast and when it is no longer being hit by it you can call whatever method you need to on it
...what? It's looking to see if the object that was clicked is the same as the object next to it... i was using the position as it is the only thing that is unique to each object
I'm wondering how to utilize Pen.current.pressure.ReadValue() effectively so that it functions as a mouse Input.GetKeyDown(KeyCode.Mouse0)
or is what it is supposed to be doing
Could u write me a short example code? I cant really visualize it
store the object you hit in a GameObject field
check if the object you are hitting is different
that's about it
and you're still not printing what was hit or even if anything was hit.
the more time you spend explaining to us why you don't need to debug your code, the longer it's going to take for you to fix your problem
true
the colliders work, the problem is just that if statement
not colliders
raycasts
and is that object that was hit at the same position as whatever that other object you are comparing it to is?
yes
prove it
and keep in mind that your if statement only works if the first cast hits something
oh that's a problem
I have a tilemap grid (3D) and now I have mostly 1x1 cubes placed on the grid, saved position in Dictionary. But imagine if I have an L shaped object that are 4 1x1 cubes. Is there a way to get what tiles that L shape is occupying? When I place the L I only check the tile I click and add to the Dict, but the other 3 tiles will still be "empty". Even if my collider check solves that problem I feel the Dict will be incomplete for other use cases.
can I link the game object in the scene to a script without dragging it in assets and making it a prefab? I get a circle with a cross if I drag from hierarchy, but when I run it I think it unlinks from the prefab.
should I be able to drag an object from hierarchy onto the first option ?
Simple question: How do I decide what asset is in the foreground respectively the background? in 2D
not if what you screenshot is an asset like a prefab
the edit didnt really helped
how can tell a script what object it's referencing then ?
can you rephrase this because the question doesn't really make sense
do you mean, "what objects uses a specific script?"
crap, i found the issue
The things you want in front go in the foreground. The things you want in back go in the background
There isn't much more to say than that with how you worded the question
one or both of the colliders was marked as IsTrigger, wasn't it?
asset may have been the wrong word. I am completely fresh to coding so my vocabulary = bad rn. I want to make a background in a 2d space. I dont know how to make one thing be in front of another. How do you put something in front of another?
they had me move the code to a parent object
the thing farther from camera goes in back, also you can sort things via sorting oreders
the player wasnt connecting bc it didnt have any code or even a reference
With 2D, you use sorting layers. Something that is not a #💻┃code-beginner concept
asset was not the problem in your original question, the problem was "in the foreground respectively the background"
but if you want to make sprites be in front of each other then you probably need to either change their sorting layer/order in layer
with the issue being known, how to i grab a specific object colliding rather than the object that has the code?
when my enemy is killed all the new ones i instantiate are on one health
or can i just move the collider location?
don't make health static and make sure you aren't cloning the dead one and instead using a prefab (or resetting the health for the newly instantiated ones)
it would have the static keyword on the variable declaration. you do not want that
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
then you're probably passing the object from the scene into Instantiate instead of a prefab
this is a script i put into a object containing a capsule
for some reason, when i read values on the WASD controls,
i think i am doing that yeah
nothing is picked up
where are you calling MyInput
Well I added a box collidor, and am not trusting the "fix"
Surrounded the player with the controllers collider
I feel like this will cause issues later, but I also need to start the next step so is it a bad idea to leave a potential break for later if it works now?
for instance, my object and camera are both at position 0 and they're not inside each other
nevermind!
Why is the canvas and legacy text so large when I create it?
Hello , If I have a value between 0 and 100 , Like say health , how can I get to be 0 - 1? should I be using Mathf.InverseLerp?
don't use legacy text, use text mesh pro . . .
just divide the current value by the total value . . .
Like currenthealt/maxhealth?
yea you can, or just divide if this case is always between 0 and X
give it a shot . . . 😉
The text is gonna be in a set place that should only be visible when the camera is moved, and the canvas being huge is the main issue
What's wrong with legacy actually?
Fixed size by linking to camera
that's how the canvas works. it's regular size in the game view. the size in the editor is huge because one pixel is one unit . . .
legacy is just that, legacy (old). text mesh pro is the de-facto norm and should always be used . . .
Wait so did I accidentally just make my game tiny?
what? no. the canvas is always huge in the editor. that is it . . .
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Ah, and I've really only used legacy for text and buttons and such, the only thing ik about text mesh is it can make more unique text with special fonts and such
And ig fits the screen automatically
it can also do lots of fun stuff, like links and rich text formatting
I feel like that's not too necessary for an arcade game
Unless it can also make pixelated text? That would be cool
it doesn't have to be. fonts look better and you can do more with text mesh pro. it's the new default and should always be used, that's it . . .
Is it not more complicated to use though? I don't honestly know the formatting to use it in code
Actually I take that bad
I have a reference of it in my last project, I'll just copy that
no, it's just a class like everything else in unity. works the same as legacy text but more options . . .
TextMeshPro is trivial to use
you have already spent more effort trying to convince yourself you don't need to use it than it takes to just use it
Your canvas is in "Screen Space - Overlay" mode.
Yeah I fixed that part
It shows up in the scene view at a size such that each pixel is one unit/meter
This isn't actually how it's going to render. The position of the camera relative to this canvas is irrelevant.
It's going to be rendered directly onto your screen (hence the "overlay" name)
I would suggest putting on 2D mode while working on your UI. That makes it easier to look at.
Ah, that's interesting then
Press F with the canvas selected to fit it into your screen
Not a good idea probably, I've been having issues where my games don't scale to my screen size and I'm coding on a TV rn 😅
My normal setup isn't accessible rn sadly
i mean, literally to make it fit into the scene view
so you can see it
you can fix this pretty easily by setting up your canvas properly
I tend to use "Scale With Screen Size" on the Canvas Scaler component
you'll find this next to the Canvas component
The camera has nothing to do with overlay canvas rendering.
Just the resolution the game's being rendered at.
The default, Constant Pixel Size, just keeps everything at a constant size
Scale With Screen Size causes things to resize as your resolution changes
The other big thing you need to do is set up your anchors correctly.
suppose you want to put a piece of text in the top left corner
So it will prevent issues like being unable to see parts of the game on smaller screens?
A common error is to just add the text and then drag it over to the corner.
This means that you're putting it a fixed distance from the center of the screen.
If the aspect ratio changes, you'll wind up with the element going off the screen
Oh, my text is generally supposed to stay where I put it, I only use health bars and scores with anchors
(and depending on your Canvas Scaler settings, just changing resolution might send it off-screen)
Oh, my text is generally supposed to stay where I put it,
but that's the thing -- where does it "stay" relative to?
Oof, that's not good
If you leave the anchor on the default settings and want your text to be on a screen edge, you'll have a bad time
Like I have a text that should only be viewed when the camera is moved closer to the object
are you talking about world-space UI here?
No idea
where you put UI elements at specific places in the world, instead of drawing them like a HUD?
Oh, then yes
Ah, okay. That's simpler.
Although, for text, you can just use a regular TextMeshPro component
there's no need to use a Canvas in World Space mode
Yeah I still don't know how to implement textmesh
UI text is a different component.
It's attached to a "Screen Space - Camera" canvas.
This canvas is stuck in front of the camera.
so, yes, it's going to move around
That linked to the canvas too
If you want text to appear at a specific place in the world, delete the Canvas and create non-UI text
you can use the GameObject menu to quickly create a new object with non-UI text on it
Would I not need the canvas to have moving code aswell?
"moving code"?
Crap
back up and explain what you're trying to accomplish
Imma need a sec to reword lmao
Don't know why I even said code there
Ok, I'm using the canvas for text that is always on the screen, (health, score, enemies left, time in game)
I am currently trying to make a text box that stays above the box, that when my character touches the box, it says a question that I can answer with one of two inputs be it y or n, if the player moves away, the text goes away aswell
I have the collision detection already
Okay, so non-UI text would make sense here. But it would also be fine to use UI text on your existing canvas. You'd just need to write code that moves the text to the correct spot.
The text showing is the issue considering I'd usually use legacy and don't know the code to use for textmesh
the code is basically identical
TMP_Text is the type to use for referencing TextMeshPro components
public Text NPCtext; is legacy right?
That is legacy text.
so i just do this? public TMP_Text NPCtext;
Correct
NPCtext.text=""; so how do i convert this?
change nothing
just try it!
this is valid; TextMeshProUGUI is UI text (and TextMeshPro is non-UI text)
TMP_Text covers both
then what are the two code lines that reffer is putting?
this is not valid
ah
it's text, not Text
$"Some text" is an example of string interpolation. It lets you include expressions in a string.
int dollars = 100;
string result = $"I have {dollars} dollars":
It's an alternative to using string.Format (or just using + to glue things together)
oh, i remember that from base c#, ive never used it in games so far, interesting
i can see a few uses for that
float number = 3.6345893468934f;
Debug.Log($"It's roughly {number:N2}");
this would log It's roughly 3.63
anyway, TMP_Text should just be a drop-in replacement for Text for common usecases
yeesh, I say old but ive only been doing this for a year...
crap, do i need a new using statement?
I can't seem to get it to work properly , If I show my script can you demonstrate it for me?
https://pastebin.com/NFKxtwwA
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.
was i supposed to configure the ide in someway? (Visual studios was installed by unity)
So I'm encountering an error with my drawing tablet code.
https://gdl.space/weqimafixa.cs
Any ideas as to why it is generating such a large surface area?
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
do this if you aren't getting error highlighting and suggestions
well it kinda worked, the text is kinda blurry
That's because your game view is scaled
now, I'm not entirely sure why that is..
try messing with the slider
it only lets me make it bigger
not really sure what part of the code you are talking about, or what doesnt work
odd bc i dont recall messing with that and nothing was being blurred earlier...
why is my rigid body dragging so hard when the drag is set to 0?
but hey, the interaction works so thanks man
im using rigidbody.addforce() to move my object continouisly
is it touching the ground? Could be friction.
like this
it is touching the ground yes
then there's friction
public static int Hero = LayerMask.GetMask("Hero");
public static int Monster = LayerMask.GetMask("Monster");
public static int Tilemaps = LayerMask.GetMask("Tilemaps");
public static int Buildings = LayerMask.GetMask("Buildings");
public static int Anything = Hero | Monster | Tilemaps | Monster;
```why am i failing to hit Anything?
also make sure that this isn't checked
this looks fine, but the other code would be relevant
I reverted it , I wanna keep the float values like health between 0 and 1 instead of 0 and 100 ... I think I had it right but the decrease was way slower then the others ... at first wasn't sure if I did currentHealth/ maxHealth in the correct spot
wait also - not sure you can use GetMask in a static context like that. @queen adder
that's illegal! 🚓
how do i fix this?
the console should have errors about using LayerMask like that
here's an alternative!
getmask works fine as static
If you don't want friction, use a custom physic material without friction
i love it when compsci people use "illegal" to refer to errors in code
public static int MyCoolLayer;
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
static void SetupLayers()
{
MyCoolLayer = LayerMask.GetMask("Cool");
}
thanks, ya fixed another one of my broken things lol
favroite word to use when talking about code
my favorite word is "bogus"
im still really not sure what code you are referring to, as anything health related isnt even in this script. and no idea what "but the decrease was way slower then the others" means. What decrease, what others? This is all too vague
cool attribut
i got errors when i tried to use GetMask to initialize a static field
now that did happen to be on a ScriptableObject that was getting loaded super early. then Unity crashed
let's try that again
not health , hunger , health was just an example
here is what I had
https://pastebin.com/gd9Lk2C8
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.
it's in a mb
ok you're definitely getting errors then
maybe because using old unity?
ah, true
ok
it could still be failing
ive confirmed its nto friction
verify that the values make sense
yep, that's OK.
go figure.
what a downgrade then
how do you make an immovable object?
all objects are, by default, immovable!
if you put a Cube in your world, it will never move.
my player just walks through the other on collision
oh, you're asking how to stop the player from walking through things
yes
You just divide the current value by the total value, and the quotient (result) is a percentage between 0-1. Make sure at least one of the values is a float. Whole numbers will yield 0 if less than 1 . . .
how is the player currently being moved?
i need to start being more clear with my questions...
transform.eulerAngles = new(0f, 0f, transform.eulerAngles.z + (Input.GetAxis("Horizontal") * speed2 * Time.deltaTime * -10));//transform.Rotate(new Vector3(0, 0, Input.GetAxis("Horizontal") * speed2 * Time.deltaTime * -10));
you need to detect things first
it detects collision
you'ld better use other system then, like physics
translate = teleport through objects
thats just my move code
use physics to move physics things
so this is just directly changing your position
try rigidbody
it has no clue what's going in the world around it
or charcontroller
you need physics for collisions
yes
i do
A rigidbody would be a good choice, yes. That will let your character interact with the physics world
rigid body
Manipulating the transform does not involve or use the physics engine at all. It does not detect collisions . . .
well you have to move it with its proper methods that respect physics then
not Transform
if you wanna make a player character move you choose to move it through a rigidbody's move method or a charcontrollers move method
or, if you insist using transform, do physics casts each time you try to move
if youre changing the position directly
thats kind of a huge no no
i mean i wouldnt know much but im pretty sure it could be tedious coding that way
Ok I got it working now but the way I'm decrementing is way too fast , would I change the rate to 0.01? or change this
ModifyHunger(-hungerRate * deltaTime);
public static int Hero => LayerMask.GetMask("Hero");
how do i fix my character sliding like a penguin? i turnt the RB drag to 0 and its still sliding
dirty xD
hands you 48 bytes of garbage
this isnt through friction however
I didn't realize you could just use LayerMask.GetMask to initialize static fields on non-unity objects
so that's probably the best way to do it
I was literally staring at the downgraded version of mine thinking this lol
I was doing it in RuntimeInitializeOnLoadMethod-tagged methods haha
If you want to have these static fields be on a MonoBehaviour, then you can use that
It's a super useful attribute. It lets you execute static methods at various points in the startup process
I use that to fire up my game controller, which loads a bunch of other stuff
well you have a hunger rate variable for a reason, change that..
it also shouldnt be changing that quickly
u2017 is a pog having no problems at static initializer on getmask though
weren't you failing to detect anything
ah that, the problem is the raycast was in wrong position 
But still, each of the ints here works fine even before the Anything was added
so i can push objects, but cant use them as walls, thats irritating considering its how i stopped my character in my last game...
imma check my old code to see what stupidity i used to accomplish that
interesting!
unity 2017 sweep
you must have been using something that actually cared about physics
most likely a rigidbody
The problem is entirely based on when the static class is initialized. As that's defined entirely by the usage, then that's where the restriction is made
Ooh, right
(statics are initialized when they are accessed for the first time)
They're initialized on first usage of the type, aren't they?
how do i fix my rigidbody addforce sliding the player?
here is my code
(groundDrag is set to 0)
ah, i didnt have my seccond square collider
wdym you want drag but its at 0?
you said rb is sliding
yeah
you need drag
drag = no sliding..
i thought drag makes the player move after there is no force
wait sorry use the friction
huh
brain fart
addForce isnt doing it at all, you are simply giving it force and never slowing the player down by yourself.
Also, you dont need to mess with drag here. You can keep it and friction at 0 if you want then do something to provide countermovement when the player should be slowing down
where is friction?
well crap
drag makes it harder for an object to move. Think of drag like a parachute attached to the object. It will even slow down the player from falling
ohh
how do i link two objects so that they cant be separated?
negative addforce?
parent them or use joints(rb)
they are parented
what does addforce really do?
does this change the velocity of my object?
it Adds Force
or does it translate its position the amount of the given variable
for instance if i am to call addforce() once what would happen
possibly a very easy and dumb question:
how do i disable the editor from responding to the alt key when in play mode? trying to test using alt as an input and it opens the editor's menus/shortcuts
disable shortcut keys
yea thats what i would do if I had to, although changing the velocity is a lot easier since you really dont need proper physics interactions most of the time
the button with crossed out keyboard
ok
so i should change my forcemode?
it adds to the velocity, in the exact same way that you could just add to it. but addforce has a few options for different formulas, in that image above.
The physics system (and rb) is what causes it to move
if you dont want any sliding / frictions just go for .velocity prob
adding drag to the floor is less tedious than manually playing with velocity
nope, no luck
alt-A is still opening an editor shortcut
are you actually focused in the Game View window? like clicked into it
yeah its a pain
until you start falling slowly due to weird edgecases
yep, cursor state is confined to the window
like when player sticks to a wall while falling?
weird, alt-a doesn't do anything for me at all when in game view
something odd on your end
i just meant on inclines or other cases where the player should be falling/sliding but is touching something
yeah i thought it was weird too
maybe its a 2023.2 issue
negative 🤷♂️

public static int Buildings = LayerMask.GetMask("Buildings");
public static int Anything => Hero | Monster | Tilemaps | Monster;
```omg... i know now the real problem...
I was testing to hit Building... it wasnt listed
actually, imma test as well if non prop works still
yea, can work without getter prop (dunno why though)
In 2D. I am trying to make 2 different objects appear at the same x level but the issue I have is that it seems that each object have their own x value. Am I mistaken?
Let me rephrase
Each object on the same horizontal line also have an independent x levels
the x axis is left-to-right. also, each object has their own position . . .
Tried to clear that up in the last sentance but it wasn't clear
@swift crag how did you try to make static getmasks earlier
I put static fields on a ScriptableObject, then a MonoBehaviour
you put it in a mb that exists originally in the scene?
yea, that caused me hiccups too just now
remaking the obstacles seemed to have solved it
apprently, mb loads all of it's static when it have an instance
or... mb really just hates having static getmasks
actually, it explicitly said here 😁 not about the static, it's just about being in a field initializer
Yes, as previously stated
Can someone help me with this code to make a camera rotate around a GameObject (Empty) it returns one error that says that I can't convert a transform to a quaternion https://pastecode.io/s/dzty46o2
you should post the actual error message and what line the error occurs on . . .
is the script you posted cameraCont? i see no code on line 18 . . .
wait, it says it's for another script sorry
yep, thought so. always read the error messages . . .
Then what's wrong with this block https://pastecode.io/s/py4q4ccm?
where is cameraCont script
the error tells you, you are using a transform where it expects a Quaternion
ok
also if its not highlighting error in !ide configure it
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
So I'm trying to get my Wacom pen working with Unity, however it does not seem to want to input as intended... any thoughts?
https://gdl.space/giqajeqoqi.cs
does Input.GetKeyUp still work with the new input system, or should i skip this part of this tutorial?
only Input is set to Both
Oh, cool. Ok, thanks
Anything in the Input class is the old system.
Ok, very good to know. thanks
Anyone here have any idea as to how to implement a Wacom pen into unity? I've attached my script above but I'm totally stuck on how to get it going
https://hastebin.com/share/ofiyimunes.csharp
is there a good way to add a delay to this script? I'm trying to make a confirmation system that you have to click twice, but they happen instantaneously. I get a type error if I try to WaitUntil the mouse button comes up.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
You're creating a whole new brush/ LineRenderer every single frame 😱
Yeah I see that
I have two prefabs, face and cube. On awake I want to instantiate 4 faces around a cube in all directions. But it is always instantiates in the direction of how the prefab was setup in editor. Even if I change localPosition to Vector3.zero, Vector3.right etc. Instantiate(randomface, gameObject.transform.localPosition = Vector3.left, Quaternion.identity, gameObject.transform); Also need to rotate the face so it faces outwards in all directions
position != direction
and that you're setting the rotation always to the Quaternion identity
so there's not really anything changing from how it's set up in the editor
Right I figured out Quaternion.Euler(0, 0, 180f);
Turns out I only need to change the euler
singleton script is the script only or the whole object the script contains ?
dont understand
singleton means there is only one instance of that class (script) is allowed in memory
need help with thing
so its saying that "Look" isnt defined under OnFoot actions but im pretty sure it is
i dunno whar do
Code?
wdym
yes yes
Kinda hard to read
yeah its just the shitty notebook app that came with whatever version of ubuntu this is
Why do you have a . on OnFootActions
how would i use code to rotate the wheel for a car suspension script i copied off youtube https://hatebin.com/pakybhrddd
the prefab is the wrong rotation when it spawns in it just lays flat on the ground
(wheel is a resized cylinder)
oh shit
i wonder if thats it
maybe
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
yes i believe so
on it
You can bind actions using FindAction
pointerPosition = actionMap.FindAction("PointerPosition");
honestly i think im just gonna find some other code to run the mouseLook off of
everything else works fine
Also onFoot.Look doesn't exist because it's not instantiated
You would see this if you had a proper IDE
That's not how the input system works
I can't even save in VS if I use PlayerInput.MyActionMap..
Oh you are generating C# classes
Yeah I don't use that
Is there something like Start() and Awake() but called even if the gameObject is not active?
I found I could do ClassName() which they call constructor, but forum said I should not do that.
No
What are you trying to do
If you just want to call a function, make a custom function and call it
I had a component for managing UI. I want this component to disable gameObject on start. This is for lazy idiot-proof and quick editing.
So I do Start() {gameObject.SetActive(false), but since Start() will be called when the object is activated, that mean if the gameObject is not active in the beginning, and then I activate it, it will call gameObject.SetActive(false). Which mean it won't be activated.
The problem is, sometimes the gameObject may be active and maybe not. If someone is making revision, it will be enabled. If they done they will disable it so it won't be dirtying up the editor.
Just move all the visible bits to a child object
Leave that child deactivated
Let the parent (with the script) be active at all times
not other script attached to the object ?
when you attach script to object, instance (component) of that script is created
Technically there's no rules about the scope of a Singleton. Generally in Unity people mean only one loaded in the game world at a time.
How would you make a collision event when sprite leaves screen?
flappy bird clone btw
Hi guys, can someone help me with this issue? when I put in the component it doesn't show all of it
Image
there are no errors
Then you know which link to click next
What are you expecting to see that isn't showing?
BTW it doesn't look like your filename matches your class name
Odd that it wouldn't show a warning then; I wonder if this is new behaviour 🤔
I seem to remember rumblings of the restriction being lifted in 2023 or 6?
Your script is "Fps C Ont" though 🤔
I never hammered down the specifics, as the only benefit would be to update my site 😛
I have no idea what that means compared to what it should be
It should be the same name as the class it contains
Whats a class?
Your filename is wrong
What should it be?
FPSController.cs
It's the thing you're writing in the script
It should be the same as in the tutorial you're following
Oh ok
I'm willing to bet money that there in fact are errors in the console
Nah it isn't
Yes, that's the problem
Ok thanks a lot this was very helpful
hi, i am running a unity3d game on linux and it is excruciatingly slow when loading scenes specifically. Everything else is fast. I built for Linux, tried Vulkan/default as the api.
Everything is fast except for scene loading which takes literally 3 to 4 minutes.
It's not even a big scene. It's the same for 4 character prefabs or 1 character prefab
GPU is Intel corporation device 46a8 (rev 0c), 16gb ram. How can i debug
Use the profiler to start with
See what's actually taking up the time
Hello, I'm making a puzzle game, and wanted to add an "undo" feature, like the game Snakebird does, yet I am finding it hard to do so. I have managed to get one "undo" working, but as soon as I want to undo 2 moves, I have no idea what to do. Here is my current code.
you need to know what is stack first
I've never heard of it. What is it?
Thanks. Still haven't read anything but could this solve the issue?
Stack<Vector3> positions = new Stack<Vector3>();
...
positions.Push(pos1);
positions.Push(pos2);
positions.Push(pos3);
...
positions.Pop(); // returns pos3
positions.Pop(); // returns pos2
positions.Pop(); // returns pos1
Wouldn't link it if it didn't
Fair enough.
can i use the profiler in a built application, or only in the editor?
Hi, learning unity by creating a simple endless runner. I have now my first part done and thats the scrolling ground. What I don't get it that sometimes there is a weird gap between the "tiles" I spawn.
Here is the code:
void Start()
{
// Initially spawn a tile
GameObject spawnedTile = Instantiate(GroundTile, Vector3.zero, Quaternion.identity);
SpriteRenderer spriteR = GroundTile.GetComponent<SpriteRenderer>();
_spriteWidth = spriteR.bounds.size.x;
_activeTile = spawnedTile.transform;
// spawn the second tile
_nextTile = Instantiate(GroundTile, new Vector3(_spriteWidth, 0), Quaternion.identity).GetComponent<Transform>();
}
void Update()
{
if (_activeTile.transform.position.x <= -_spriteWidth)
{
// when the left most tile reaches the end spawn a new tile and switch active and next
// sometgimes gap, why?
_activeTile = _nextTile;
_nextTile = Instantiate(GroundTile, new Vector3(_spriteWidth, 0), Quaternion.identity).GetComponent<Transform>();
}
}
The gap looks like this (see image)
I made it work with the workaround in the if statement in the update method doing this if(_activeTile.transform.position.x <= -_spriteWidth + 0.2f) -> But i really want to know why i have this problem in the first place. It's not logical to me
ok stupid qn i found how to autoconnect profiler on build
You're only checking if the active tile x position is "somewhat" less than -spriteWidth (not exactly equal, and it will never be) and then spawning a new one at the x position of spriteWidth. It's not going to align the new tile to the old one for you
Spawn the new tile relative to the old one
new Vector3(oldTileXPos + 2 * spriteWidth, 0);
Thx thats it. Did it like this and now it works like a charm _nextTile = Instantiate(GroundTile, new Vector3(_activeTile.position.x + _spriteWidth, 0), Quaternion.identity) thx 🙂

But still not 100 % sure why I had that problem. Is it because update is called too often and hence it's not precise enough?
you can duplicate the background eg AABC=>AABCAABC, once the first AABC less than some threshold or you see the second AABC then shift the first AABB to initial position, then you dont need to instantiate many times and use only one gameobject
It's never going to be precise enough
ok I thought that. Previously I also added the move logic of the tile into LateUpdate for science, that made it slightly better 😄
If you want something to be right next to each other then you need to spawn/move it relative to other objects in your scene or have some kind of grid/coordinate system
if x<10 x can be 9 8 7 6 5... , that mean you cant just hardcode the value
Basically imagine you have a huuuge lag spike and you're moving your background using transform.position = Time.deltaTime * ...
It's going to fly off the screen and then spawn a new tile way further away from the old one, because technically it did go past that hardcoded x pos value and the spawn is not relative to the old tile
ok that makes sense now thank you very much
that explains why the gap varied in size, since the framerate is not always the same fps
Hello, i am making a endless runner game and took this code of the internet it supposed to generate levels aotumaticly and delete the old one,but, when i hit save code and go to unity to check it out the console stops me and say " invalid token";" in class, record, struct, or interface member declaration" i tried to at least know what is the console yappin about
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
I understand stack now, but how would I use it if I were to create new Vector3s for every move, and how would I push in these new Vectors out of the Start void? I understand everything else, like popping them and changing the position to the last Vector 3, but the video I watched and article you sent has already defined variables, so it was easier.
It's funny now that I changed the movement of the tiles back from LateUpdate to Update - now I have a gap again O.o although I add new tiles relative to the old one. How's that? When I change it back to LateUpdate everything works
Simply push the current position onto the stack right before making a new move
Stack<Vector3> previousPositions = new Stack<Vector3>();
void Move(Vector3 position)
{
previousPositions.Push(transform.position);
transform.position = position;
}
void TryUndoMove()
{
if (previousPositions.Count == 0)
return;
transform.position = previousPositions.Pop():
}```
An issue I was having is changing the Stack out of the void, so by simply "creating" the stack out of a void can solve this issue?
What do you mean by "out of the void"
it is called method not void, void is return type
if you mean "create the stack" as in "create an instance of the stack" then you can simply do as I've written above, right after declaring the stack field, in the same line
or in the Start() method, same result
Yeah that's what I meant with "out of a void"
all my files are missing in the editor
I'll see if I can get it working now. Thanks.
my files are gone in editor but in file exploror they are still there what happened help pls
i was just switching to webgl so i could put a build on itch.io for playtesting and they all dissapeared
but my game still works
where is bug report
Just a reminder that value type fields are always initialized with their default value / default constructor so you don't need to initialize them in order to use them. Reference types (classes) on the other hand have a default value of null so you always have to explicitly call out their constructor before use, so either inline with the declaration or right before you need to use it
Good luck with the rest
Why doesn't this work? https://docs.unity.com/ugs/en-us/manual/authentication/manual/platform-signin-username-password
await AuthenticationService.Instance.SignUpWithUsernamePasswordAsync(username, password) it shows error that Authentication doesn't know this function
screenshot Project Settings->Services->Authentication
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Hi, im making an 3D level editor, and i want spawned object to have Y pos same as Y pos in prefab, but it sets to 0... btw i didnt make this code, this is from tutorial, but i changed it to work with multiple grid layers, and when i spawn prefab it have correct Y pos, but when i drag it it changes to 0
Here is code:
BuildSys: https://hatebin.com/kaftarbzwa
ObjDrag: https://hatebin.com/fegqpovnbb
i was trying to fix that myself but it was too hard
I would suggest that you add some debugging into GetWorldMousePosition and SnapCordinateToGrid so you can see what is happening
lemme try
should have been your first action
and what im gonna do with it lol
it always giving me different Y
lemme try smth
nah, didnt help
i think something sets it to 0, like grid...
that is the point of debugging the code, so you can see what is happening. show those 2 methods again
but is celPos correct?
its not cuz of celpos i guess
it even sets Z to 0 everytime
maybe in ObjDrag i need to add og object Y to offset
not to offset
finally
i fixed
in line 33 i make it count og Y pos too
thank you for help
Hi
Having a bit of trouble
I'm starting off on unity and just playing around with making a 2d platformer and rn I have 2 portals, like in the image
I managed to code it so that when the player touches the bottom portal, the square appears in the top portal
but now I want to make it so that you can go back and forth between portals
I tried
any portal should have outcome
reuse it and add a delay
but then it's jsut an infinite loopp
add a delay so u break the loop
I tried removing/putting back IsTrigger but I don't think I did it right
how do you add a delay?
google it
alr
because once it goes to portal B, it'll fit the conditions to go to portal A, which it'll send it back to portal B
and it'll just go back and forth
then have a bool
look up a basic couroutine that will flip a boolean to disable the portal for like 2 seconds once teleported
I did do that
so you portal
and canTeleport = false
you exit the portal trigger, set it back to true
{
if(collision.gameObject.name == "PortalExit")
{
portals = true;
}
else
{
portals = false;
}
}```
this was the code
then in another script I did this:
{
CC = GetComponent<CircleCollider2D>();
}
private CircleCollider2D CC;
public InteractPortal triggering;
// Update is called once per frame
void Update()
{
if (triggering.portals)
{
CC.isTrigger = false;
}
else
{
CC.isTrigger = true;
}
}```
ever
how can I do it then?
for ur simple project just do a tag check
changing asset file
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
id recommend following a youtube video on how to set up teleporters
you will learn the proper approach
what u did for a beginner is great tho
keep trying your own methods
Stupid question, but how do I call a void that contains parameters? I want to call the Move void but it gives me an error. Here is the code:
void Update()
{
if(greenSlime.isMove == true && canUndoSave)
{
Move();
canUndoSave = false;
}
}
public void Move(Vector3 position)
{
previousPositions.Push(transform.position);
transform.position = position;
}
void is a return type
Look at the parameters between you calling your method and the parameters of the method. If it expects parameters, then you need to send something of that type into the method.
hey guys I'm trying to make a video play audio but it won't work. I'm using the video player component, which plays the video fine, but no audio will play even though volume is on 1 and not muted (yes, i have audio listener on camera)
getting this error as well when I'm, trying to play example video in editor (outside working project)
You need to pass it a Vector3 value. e.g:
Move(new Vector3(1, 2, 3));
or
Vector3 position = someObject.transform.position;
Move(position);
unless you can provide code of the problem, otherwise #💻┃unity-talk or #🔊┃audio
no code involved. simply dragged a video on an object and wont make sounds :C. should work just like this
my bad just realised this is code-beginner thx
Thanks. Made it work by just using the transform.position
Consider taking a pure C# course first if calling methods with parameters is already an issue.
Learning the basics first will definitely help. Otherwise it's kinda like trying to build a house without knowing what materials and tools to use, so you try and learn both at the same time and end up with a lego shack using random pieces from several lego sets sticked together using glue and tape instead of a proper brick house
Heard that w3schools C# course it good
Yeah, I've realised that I'd probably need it after having this conversation. Thanks for the help and advice.
why the unity executes this code section even though it shouldn't
u should be getting an error with that ; behind if
no, it wont cause any error
rly?
just fail silently
my bad, thank you
oof it got deleted
There's no crossposting here. #archived-code-advanced
Is there a way to initialize the fields of a class before Start is called but from the outside?
Like if I have a board and I don't want it to be of a fixed size, so I want to provide the height and width from the outside.
You can expose the fields in the inspector and set it manually. Or you can assign it in Awake function.
Right but even in the Awake method they would have to be known in advance, I wouldn't be able to set them from outside.
define 'outside'
For example if I'm generating a level and the player gets to freely pick the size of the board. I can't have those be stored in the board class.
Like this ^
why not?
You store the choice the player makes, somewhere. Such as in a GameManager, and read that when initializing your board.
So the value has to be read by the board class itself?
What I'm looking for is to call the constructor of the board class and provide the dimensions that way, but with MonoBehaviour that's not an option.
if your board is a prefab you can inject the values into the prefab immediately before instantiating it
Awesome, that's exactly the case. How do I do it? I tried using Load and then Instantiate but that does not seem to work.
In code that is, not by assigning in the editor.
GameObject prefab;
...
Board board = prefab.GetComponent<Board>();
board.height = ...;
board.width = ...;
GameObject go = Instantiate(prefab);
GameObject gridBoard = Resources.Load<GameObject>("Prefabs/GridBoard");
gridBoard.GetComponent<GridBoard>().Init(10, 10);
Instantiate(gridBoard, Vector3Int.zero, Quaternion.identity);
Did you mean something similar to this? ^
maybe, it depends what Init does
sets the height and the width, but it doesn't work, Start gets called before that
but you should not be using gridBoard after instantiation
also why Resources.Load just set gridBoard in the inspector
Start isn't called immediately after instantiating. You can set the values after the Instantiate line.
Start is being called on gridBoard because of the Resources.Load
I think that is where the confusion is
[SerializeField]
GameObject _gridBoard;
// Start is called before the first frame update
void Start()
{
_gridBoard.GetComponent<GridBoard>().Init(10, 10);
Instantiate(_gridBoard, Vector3Int.zero, Quaternion.identity);
}
Welp, this also doesn't work.
Or wait, I'm still using _gridBoard
again what is Init doing, show the code
public void Init(
int width,
int height
)
{
_boardWidth = width;
_boardHeight = height;
}
that's fine, so now you just need the GameObject returned from Instantiate
I'm confused. We assign the prefab in the editor -> set values in its script -> instantiate the prefab and only at that point does Start get called?
yes
i got this error when loading a scene in editor
ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
details
System.Collections.Generic.List`1[T].get_Item (System.Int32 index) (at <605bf8b31fcb444b85176da963870aa7>:0)
System.Collections.ObjectModel.ReadOnlyCollection`1[T].get_Item (System.Int32 index) (at <605bf8b31fcb444b85176da963870aa7>:0)
UnityEngine.Rendering.HighDefinition.StaticLightingSky.InitComponentFromProfile[T] (T component, T componentFromProfile, System.Type type) (at ./Library/PackageCache/com.unity.render-pipelines.high-definition@14.0.8/Runtime/Sky/StaticLightingSky.cs:228)
i cant find where is that "static light"
[SerializeField] private GridBoard _gridBoard;
void Start()
{
GridBoard board = Instantiate(_gridBoard, Vector3Int.zero, Quaternion.identity);
board.Init(10, 10);
}
This is all you need to do
How does that follow? GridBoard is a script, Instantiate returns a GameObject.
No it doesn't, it returns whatever you pass to it
no, Instantiate returns a copy of what you instantiate
Then here the last line should have been Instantiate(board);?
(probably) could be if you wanted
But Nitku pretty much provided the easiest solution
In that case no because the previous lines modify the prefab
but there's no reason to do that in this case
At this point I'll just post all the code:
GameManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour
{
[SerializeField]
GameObject _gridBoard;
// Start is called before the first frame update
void Start()
{
var board = _gridBoard.GetComponent<GridBoard>();
board.Init(10, 10);
Instantiate(board, Vector3Int.zero, Quaternion.identity);
//_gridBoard.GetComponent<GridBoard>().Init(10, 10);
//Instantiate(_gridBoard, Vector3Int.zero, Quaternion.identity);
}
// Update is called once per frame
void Update()
{
}
}
GridBoard.cs
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;
public class GridBoard : MonoBehaviour
{
private int[,] _board;
private int _boardWidth;
private int _boardHeight;
[SerializeField]
private Tilemap _tilemap;
[SerializeField]
private Tile _whiteTile;
public void Init(
int width,
int height
)
{
_boardWidth = width;
_boardHeight = height;
}
void Start()
{
Debug.Log(_boardWidth);
Debug.Log(_boardHeight);
_board = new int[_boardWidth, _boardHeight];
GenerateTileMap();
}
private void GenerateTileMap()
{
for (int i = 0; i < _boardHeight; ++i)
{
for (int j = 0; j < _boardWidth; ++j)
{
_tilemap.SetTile(new Vector3Int(j, i, 0), _whiteTile);
}
}
}
}
The console always prints 0 0, it doesn't set the dimensions.
So did you try what I suggested?
Simply instantiate the board and call Init on the new instance
Already tried
Has anyone ever experienced this? I'm destroying all objects with a certain tag, then straight after, running a Find for all objects with that tag, checking the Length of the array, and seeing that all the objects are still there?
the order of method calls will be Awake, Init, Start
Show what you did
Destroy is delayed until the end of the frame
Interesting, thank you.
How can I set GridBoard from the editor?
Simply drag the prefab with that script attached
...the same way you set it when it was a GameObject?
I can drag the prefab, which is what I'm currently doing. It has a script attached to it called GridBoard.cs
Then what's the issue
methods?
Right...
Guess this has hit a dead end. I appreciate the help regardless 👍
- Assign prefab in inspector
- Instantiate prefab in code
- Call Init on returned copy
Show code where it prints 0 0
im trying to make a scene that displays certain values about the player's attempt at a stage, e.g. their name, scores, etc.
could i ask for suggestions on how to make the scene create a new button that is created for each attempt of the player? sort of like a spreadsheet and its tabs
Instantiate prefabs into a layout group
OK, so having given this one last try it finally worked. So @modest dust and @keen dew were right, although I'm still not sure how it's possible to drag a privately defined class (=GridBoard) into the editor like @keen dew said and why it makes sense to instantiate it instead of a GameObject.
It's possible to drag it because the [SerializeField] attribute literally means that
When I tried it before I simply ran Init() on the script of the prefab, which was confusing to me then and now it makes sense because it's simply the wrong thing to do xD
What would I be dragging, the script itself?
and it makes sense to instantiate the class you want instead of GameObject because then you don't need to do an extra GetComponent on it
You'd still be dragging the same object but you get direct access to that specific component
This is... weird. Prefabs just fill in whatever role we need it to?
no
So long as a prefab has that script it attached it can be dragged into that slot?
yes
It might be defined privately, but it still inherits from built-in types
You're already doing the same thing in the other script
[SerializeField]
private Tilemap _tilemap;
[SerializeField]
private Tile _whiteTile;
those do the exact same thing but with Tilemap and Tile instead of GridBoard
Why does instantiating the prefab or the script attached to it achieve the exact same result? Because in reality the dragged object is still the prefab?
In this script I dragged the tilemap and tile directly
Yes, and both of those are GameObjects like everything else
how would i get the exact center between 2 objects?
Add their positions and divide by 2
ok now i feel dumb
Two reasons to use a concrete type instead of a vague GameObject:
- No need to use
GetComponent<T>()since Instantiate already returnsT - You won't be able to drag anything you want into that slot in the inspector, by accident or not, only compatible types
How does it follow that Start is called after my Init method from this description:
Start is called on the frame when a script is enabled just before any of the Update methods are called the first time.
Is it just that a given Start method is guaranteed not to be interrupted or something? So if we call Instantiate and then Init within the same scope there won't be a problem?
you're going to have to show us your code
Init is not a method Unity knows or cares about
Start runs on the next frame after instantiation, before Update runs
If you mean you're doing something like this..
var obj = Instantiate(thing);
obj.Init();
then yes, it's expected for Start to run after Init
oh, that's interesting -- I went and tested to be sure. I didn't know that Update didn't run on frame 0!
I guess the gap in my knowledge (one of many) has to do with frames. A frame cannot change between these two calls?
Unity is single-threaded. You can't have two things "happening at once"
From what I gather the only guarantee is that Start gets called before the first Update, so it doesn't necessarily run from frame 0
