#💻┃code-beginner
1 messages · Page 557 of 1
how can i know whats going to be the last screen scalling?
looks right in 1x scaling but bad with 0.25x
how do i know where i should place this chatbox
could anybody try helping me
not understanding really but for pixel art, make sure everything is at 1 scale
and make the images you import the exact pixel size without scaling
for example 8x8 is just 8 by 8 pixels
alight thank you
yeah i have got that
drawing and importing stuff
another little issue tho
do you know why its showing this X?
only happens when i set ref resolition to 1920 x 1080
I either dont know how to implement/use this or its not working. Dx this has stumped my progress for a week.
what's your code?
nah idk maybe those are 0 opacity pixels or smtn
alight
mine? one sec
how are you moving the object. show your !code . . .
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/ , https://paste.ofcode.org/ , https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
yes yes, wait, it takes time
thing is that if i set a diffrent resolution 1x is diffrent
the X means that either the width or height of the object is negative
its a setting on your canvas
scale with pixel size or something like that
Ok the first link is where I apply the orientation to the player gameObject (which is working): https://paste.ofcode.org/LspRRFjNqhU9Tjcyu5Zn7M
The Second link is my whole player movement script (some variables might be unused): https://paste.ofcode.org/3658hhPyK4tGhk69psEZ55T
its not negative
you need to have a CanvasScaler component so that the UI scales properly
TransformDirection doesn't do anything, it just returns the equivalent position
you haven't actually changed anything
you need to do totalMovement = transform.TransformDirection(...)
i added it but
I will try that!
try clicking the blue arrows on the transform component and select the red center one, then you should be able to visualize the negative components
what do i need it to change it to
@brittle maple also note that TransformDirection has an overload to accept x, y, z separately, so if you feed the direction in directly you don't have to wrap it in a Vector3
yeah it needs to be on the Canvas only, not on your image
then you should configure it properly
does that fix the resolution issue? thats what i was tryna do
Ok, what am I supposed to put in the brackets () ?
the direction in local space that you want to turn into world space
I would also suggest not changing the image scale manually, always leave it as 1
and check what's causing the negative height/width, otherwise it might not work as expected
and it would probably be better to move this question to #📲┃ui-ux as it has nothing to do with code
one tiny question, if I was to put gameObject.transform.rotation, it would get the rotation of the object that my script is attached to?
that will give you the Quaternion value. that is not what you want . . .
put it... in the function?
that doesn't make sense
Yes, it is my first time using the TransformDirection, nothing makes sense!!!
also, you don't need gameObject, you can just do transform.blah . . .
did you read the docs i linked you?
I get that it turns local space into world space and vice versa, but I dont even know the difference between the 2
TransfromDirection just turns a local direction into a world-space direction
linearVelocity is world-space
currently, totalMovement is local-space
world space is just the space of the world
the local space is the space relative to the gameobject. the gameobject is at the origin of the localspace, and the local space moves and rotates and scales along with the gameobject
ok im following, I just need: totalmovement = transform.transformdirections(something, something, something);
and those somethings would be what you had inside the new Vector3 that you assigned to totalMovement before
Im sorry for wasting your time, but you are saying that I should put the same things that I put in "totalMovement"s Vector3?
yeah, then you won't need that first assignment
That didn't work.
"didn't work" doesn't really tell me anything
heyy!! i was here awhile ago and had a bug that i couldnt fix and never got it fixed.
could anyone help me with a raycasting script absolutely refusing to work? i've followed a good bit of tutorials and don't know a ton a bout raycasting
my goal is f or the player to look at an object, and press "E" and upon doing so it responsds with Debug.Log("hi");
Sorry, the problem still persists, my camera Y rotation isnt having any effect on my movement direction, sorry again.
ALSO SORRY TO INTERRUPT YOU CAN IGNORE ME !!
stop with the caps, please . . .
what's your current code?
just the Update code is fine, you don't need to show the whole script
one sec.
"doesn't work" doesn't give us any info, have you tried debugging at all?
what's your code?
sorrry uhhhh heres the script for the camera
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
interface IInteractable
{
public void Interact();
}
public class Interactor : MonoBehaviour
{
public Transform InteractorSource;
public float InteractRange;
LayerMask _mask;
private void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
Ray r = new Ray(InteractorSource.position, InteractorSource.forward);
if(Physics.Raycast(r, out RaycastHit hitInfo, InteractRange, _mask))
{
Debug.Log("raycast hit");
if (hitInfo.collider.gameObject.TryGetComponent(out IInteractable interactObj))
{
interactObj.Interact();
}
}
}
}
}
andd heres the script for the object that is being interacted w ith (and yes, i've tried debugging)
using UnityEngine;
public class TestInteract : MonoBehaviour, IInteractable
{
public void Interact()
{
Debug.Log("hi");
}
}
so I play this sound every time the player jumps:
public void OnJump()
{
if (body.gravityScale == 0)
body.gravityScale = gravityScale;
body.linearVelocity = new Vector2(body.linearVelocityX, jumpForce);
audioSource.PlayOneShot(jumpSound);
}```
however, the sound plays twice, is there a reason why?
Aight, so its solved (I hope forever) In all this code messing I seem to have deleted the part that was rotating my Player gameObject, I will do some debugging and testing, thanks!!!
place a log inside the method. see if it appears in the console twice . . .
this happens every time you jump?
if so, then you appear to be jumping or pressing the button three times . . .
i don't think so
how do you track the button press?
if you hold the button down, does it keep logging?
nope
do you have duplicate PlayerInput scripts on other GameObjects?
wait i think i know why
its because im jumping every time the key is interacted, rather than only when pressed down
now the player doesn't jump at all
public void OnJump(InputAction.CallbackContext context)
{
if (context.started)
{
if (body.gravityScale == 0)
body.gravityScale = gravityScale;
body.linearVelocity = new Vector2(body.linearVelocityX, jumpForce);
audioSource.PlayOneShot(jumpSound);
}
}```
Does anyone know how to take a picture over terrain?
sorry to pester here again but does anyone have any idea why this ray isn't working?
do you get any debug logs in the console Zack
None
your LayerMask is not assigned
[SerializeField] LayerMask _mask and assign the layermask from the inspector
also make sure you interactables have a collider
and first parameter inside the Raycast has to be a Vector3 not a Ray
what should my layermask be?
i had it on "everything"
i am really surprised you dont have any errors
well a layermask for all of your interactables.
which line..? (sorry i feel dumb rn)
Ray r = new Ray(InteractorSource.position, InteractorSource.forward);
this one?
(Physics.Raycast(r, out RaycastHit hitInfo, InteractRange, _mask)) < this
oh
i highly recommend you learn the docs if you dont fully understand. https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Physics.Raycast.html
Hey quick question. Trying to put my prefab text (the HandValueText) into the cardimagerandomization script (I know that wording is weird, but that script has the handValue already in it.) HandValueText is TextMeshPro, but whatever I set the script class to, it won't let me put HandValueText in there. Any ideas?
Code:
public Text handValue;
public void Start()
{
hand = GameObject.Find("HandPosition");
AddCardImage();
hand.GetComponent<CardValuesScript>().handValue = hand.GetComponent<CardValuesScript>().handValue + cardValue;
Debug.Log($"CardValue " + cardValue);
UISprite.sprite = cardSprite;
handValue.text = "HandValue: " + hand.GetComponent<CardValuesScript>().handValue.ToString();
}
``` Thanks!
u said its textmeshpro but in the script its public Text
isnt that the built in unity one
Mhm, I just dont know what do put there instead of text. I've tried TextMeshPro, TextMeshProGUI, and TextMesh too
also brother just make a variable so u dont have to getcomponent so much
ur looking for TMP_Text
also remember using TMPro
don´t you have intellisense
I do - just didnt copy over right here
as asa said, import the namespace TMPro
Sorry, still new to all this 😅 It worked, thank yall!
ur good
i just read a bit and l ooked at examples
im still not understanding sorry-
then mate you really have to learn the basics of c#
and fix your IDE so you see the console errors, ther eshould be at least 2 in your case
no i mean- ugh i know the basics of c# im just not understanding why this still isnt working
i do see console errors, just the specific script i sent you doesent have any
do you have console errors enabled
yes
fix those errors cause it might stop other code from executing no?
like if u call a function after the error
how comes it doesnt show you any errors. did you actually put your script on any gameObject
no- i dont have errors right now but i have had them in the past
like if i write something stupid right now itll give me an error
i put the interactor script on my camera, and t he testinteract script on a cube
I am making a Multiplayer FPS Shooter but i get this error and i cant fix it
#archived-networking Saku
Could try the photon discord server or #archived-networking
Okay
theres nothing in the console apart from just some lighting warnings (my lighting is super unoptimized atm)
Hey, can I still do this if Im trying to change the other script? Basically, I have a variable in the other script, and just want this item to add it's value onto that. Do I just do
handValue = hand.GetComponent<CardValuesScript>().handValue;
handValue = handValue + cardValue;
Or do I have to do something else?
For context so you don't have to scroll, here's my current code:
public void Start()
{
hand = GameObject.Find("HandPosition");
// handValue = hand.GetComponent<CardValuesScript>().handValue;
AddCardImage();
hand.GetComponent<CardValuesScript>().handValue = hand.GetComponent<CardValuesScript>().handValue + cardValue;
Debug.Log($"CardValue " + cardValue);
UISprite.sprite = cardSprite;
handValueText.text = "HandValue: " + hand.GetComponent<CardValuesScript>().handValue.ToString();
}
``` Thanks!
When I did do it though, it wouldn't change the handValue, that's why Im asking.
You probably changed the value for a different object.
text kinda looks low quality any fixes?
- use a layermask for your interactables
- make sure they all have a collider
- in your script assign the layermask as i showed above
- use a position as fist parameter in your raycast method not a ray or direction.
handValue is a value type. you have to access it from the other script and assign it. if you store the value in a separate variable (like your code above) and change that variable, it will not affect the value from the script because it is a separate copy . . .
Make sure you're using TextMeshPro Text, and that you're not scaling it down but reducing font size instead
i am using legacy maybe thats why
Indeed
TMP is better and replaces legacy entirely with minimal code changes to apply: change Text into TMP_Text and add using TMPro; at the top
So should I just keep it like how it is, and not change it into a variable? Is that still okay, even if it uses GetComponent()? (Is GetComponent() generally bad?)
i swiched to textmeshpro anything more i need to do?


- if you mean adding
[SerializeField]then
- could you show me what that would look like?
you need to store CardValuesScript in a variable to avoid calling GetComponent multiple times. then you can use the variable to access any public field on that script . . .
Replace all legacy text with their TMP counterpart
You'll need to create a font asset if you want your old font
Alright, thank you so much!
i have font i want to use imported
this picture i sent "New Text" is textmesh
if(Physics.Raycast(transform.position, direction, out RaycastHit hitInfo, InteractRange, _mask))
then you need to create the FontAsset for it . . .
Right-click the font in your Assets, and select Create > TextMeshPro > Font Asset. This will show an importer window, leave the settings as is or change them if you want, and confirm. This will create a Font Asset file along your original font file, you can then drag-drop it in the TMP Text on your object
do i need to make a variable for direction?
alight thanks
not sure which direction you want to raycast , try transform.forward
uh it still doesent work im getting 0 logs
maybe its still something w ith the l ayer mask???
what specifically did you want for each layer-
or for each object i mean
did you create a new layermask in your inspector and then assigned it to your interactables
Alternatively you can try without passing the layer mask in Raycast and see if it works again. If it does, then the mask is faulty
Also make sure the distance is big enough in the Inspector
yes and yes
and my interact range is at 100 r ight now lol
You can use the Physics Debugger window to visualize the raycasts, or use Debug.DrawRay() to do that "manually'"
if your camera doesnt have a collider you could use what SPR2 said without using a lm
didnt know y ou could do that actually lemme try that
how would i do this?
Just don't put _mask in the argument list for your Raycast
still not working unfortunately
Then use the physics debugger to see where your ray originates from, and where it goes
(assuming "not working" as "no error, but raycast does not hit anything")
i couldnt figure out how to make it work-
yes
There are plenty of resources online showing how to use the physics debugger
ykw yeah u right
would it be something like this?
Debug.DrawRay(transform.position, interactObj.transform.position);
No, it takes a start position and a direction scaled with a distance: https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Debug.DrawRay.html
so like this ?
The example you copied from this page works in your case because both do the same thing
Make sure you understand code you're copying
yes i do understand this
atleast i do now lmao
also
oh wait nvm i did smth stupid hold on
OH MY GOODDD A RAYY!!
gamedev, am i right?
Good, now replace the * 10 in the code by * InteractRange and try again, just so the line adapts to the actual length of your raycast and not just 10
done!
it is now 100
So, is the ray originating in the right spot, and going in the right direction?
Anyone here know anything about gorilla tag fan games
yes
Pretty sure they have their own Discord server for this
Post your up to date code here once more
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.Rendering.Universal.Internal;
interface IInteractable
{
public void Interact();
}
public class Interactor : MonoBehaviour
{
public Transform InteractorSource;
public float InteractRange;
[SerializeField] LayerMask _mask;
private void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
Ray r = new Ray(InteractorSource.position, InteractorSource.forward);
if(Physics.Raycast(transform.position, transform.forward, out RaycastHit hitInfo, InteractRange))
{
Debug.Log("raycast hit");
if (hitInfo.collider.gameObject.TryGetComponent(out IInteractable interactObj))
{
interactObj.Interact();
}
}
}
Vector3 forward = transform.TransformDirection(Vector3.forward) * InteractRange;
Debug.DrawRay(transform.position, forward, Color.green);
}
}
The line that says Ray r = ... can be removed as you're not using it
Then place a Debug.Log where this line was, just to make sure the code is running when you press E
oh wait yeah you are so right
IT ALL WORKS
ITS ALL WORKING NOW
WHAT
dude tysm
Put the layer mask back in and you should be good
it works :)
now time t o figure out how to make it outline something when l ooking at it !!
ehhh i have pretty detailed models wouldnt it mess up those?
im looking into downlaoding quick outline rn
no you can change the overlay color it would still visualy change but just recommended it.
hi y'all, I am trying to display a wireframe cylinder around a target person in AR (passthrough), however the cylinder in unity has too many wires in wireframe, is there a way to have something with less wires? Can I choose to reduce the number of displayed wires ?
how can I prevent this from happening?
Hey so im trying go get visual studio to do code completion and it just wont for me. I looked online, i changed the external script editor to visual studio in tje preferences, i updatwd visual studio, and it still wont work. i dont know what to do and its making me very frustrated
!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
i went there and did that, it didnt help
close everything and restart 🤷♂️
back to all of my stupid stupid code (this is probably a stupid question)
how would i trigger another public void when im NOT looking at the object? (this was my only solution to unoutlining the object sadly)
use an else statement in your raycast
yes thats what i tried first but the "interactObj" doesen't exist in that context
{
if (hitInfo.collider.gameObject.TryGetComponent(out IInteractable interactObj))
{
interactObj.Interact();
}
} else {
interactObj.UnInteract();
}```
you can cache the object outside of the scope
i uh dont know how to do that
i will leave that to you, don´t want to spoonfeed too much
you clearly lack of c# basics
i mean this is the code-beginner channel
besides i know c# basics ive j ust never had a need to learn caching with w hat im trying to do
i mean i ve been programming for what- 10 days?
when you say interactobj,Interact you save this thing outside ,the type is IInteractable
ive been tinkering with it for awhile and cant figure it out
hii can anyone guide me on how to use the input actions to create a visual script for player movement in 2d (platformer)
you could use Input.GetKeyDown(KeyCode.X) and then replace X with whatever direction your going
that , or you could use Input.GetAxis('axis') and replace axis w ith the axis your using :)
checkout #763499475641172029
im in it theyre inactive
i wanna use the new input system and that wouldnt go with it
idk how to use the new input s ystem unfortunately
\
lemme see if chatgpt can help
just wanted to point out: creating a class-scope field (variable) or caching is part of the basics. one of the first things you learn. i recommend to continue going through the basic tutorials whilst you work in unity . . .
isGrounded = Physics.Raycast(transform.position, Vector3.down, playerHeight * 0.5f + 0.5f, ground);
anyopne knows a better way of ground checking
Make the raycast originate from a bit higher so it can't start inside another collider (which it would not detect)
And make the distance so that it goes just a bit outside the player's collider
I prefer spherecasts though - they can't go thru small holes
yes maybe spherecast will work better
Another way that some people do is to have a trigger collider at the bottom of your character and use OnTriggerEnter/Exit
I find that more fiddly
CheckSphere is an option too.
Hey anyone knows where to get if this box is toggled (Custom Volume Component)?
I think that's just .active. If not, I can check in a moment
Did you add your own "active" variable?
i thought so as well but somehow .active wont change if i toggle the box in the VolumeCOmponent class its also just defined but not used somewhere afaik
i restarted my laptop and even took a nap, still nothing
How do you know that .active is not changing?
When you toggle it
i logged it
Show how you log it
What is the type of stack? I guess this is some newer API
Didn't know you can use GetComponent with volume profile components 🤔
Ok looking at doc now https://docs.unity3d.com/Packages/com.unity.render-pipelines.core@7.1/api/UnityEngine.Rendering.VolumeManager.html
Yeah it's a bit different from what i have used.. not sure right now
all good thanks i changed to unity 6 yesterday i will have a look at it again
Could try logging the GetInstanceID of the effect before and after, just in case it actually disables it but swaps to another one...
I need to look more into how the VolumeStack works
can someone help me i am using new inputsystem and would like to use crouching so when i press button it stays in crouching and when i pres again it goes back to normal what should i use in the new input system
The standard button, and you handle the toggling logic in the code using a bool variable
input action no actions found. but i have made an input actions file and attached it to the player
Wild guess: make sure "Generate C# class" is check in the Input Actions Asset you're trying to use
Visual Scripting questions are better asked at #763499475641172029
theyre soo inactivee
Here is for C# questions, either wait or use C# instead :)
i googled a bit more and found this
How I solved my issue:
Go to the file which appears as Miscellaneous Files inside Solution Explorer.
Right-Click file and select Exclude from project.
Right-Click your project/folder where the file was and click add Existing Item, and add the file you just removed back into your project.
but i dont know what this means or how to do it
This will most likely reload the project and will fix the issue yes. Another option is to open the Solution Explorer in VS, then check that the projects are all loaded: none of them should say "unloaded" or "incompatible". If some do, right-click and select "Reload with dependencies"
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
use a better bin site than pastebin 👇 !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/ , https://paste.ofcode.org/ , https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
i ended up just deleting and restalling visual studio and it works finally oml
hello unity discord, if I want to check that this object is in front of another object in a collider, how would I do that :? Is there a method I can use?
depends on the actual use case. but the best option is likely going to be a physics query like a boxcast or overlapbox
okay I'll look those up! Basically what I want to do is if it detects there's something in front of the object it's going towards, it will stop
yeah then a raycast or boxcast would likely be the way to go (or circle cast if you want it to match the circular shape), you'd have information such as how far in front of the object the obstacle is and other useful stuff that you might end up wanting to use
Okay, thanks a bunch!
if ur wanting to use the collider u have there in the screenshot
its OnCollisionEnter2D() for regular collision
or if its marked as Trigger OnTriggerEnter2D()
if thats 2D... if its 3D just -2D from the method
but other methods are above ^
Yeah It is 2D, I have those down, now I just want to check if there's a wall in front of the purple object in the collider so it can move around it, since once the purple object is in the collider it will go towards it
im gonna look up raycast and boxcast
Yup, a cast sounds more suitable for what u described.. 🍀 good luck
Thank you! :D
question, whats the best way to implement multiplayer on my game? i saw a tutorial using photon but i saw a devlog where the guy complained a lot about it, which one should i use??
people are going to complain about every multiplayer system :p
the best is always going to be the one you've researched most thoroughly and aligns most closely with your plan for your project
What's the best paint for me to use in my construction project?
There is a free asset called Alteruna on the assetstore that should have easy multiplayer, but I don’t know how advanced or scalable it is. Still maybe worth trying out.
i see, its a more personal choice, alright, thank you guys!
ill take a look on the options and see theirs pros and cons, just looking for something small right now, like, 2-4 players at max
No, it's more very specialized to the specific game you are making and its requirements
Player count being just one of a hundred parameters
only using player count as a parameter, what would you recommend?
Netcode for gameobjects
try unity's new multiplayer solution . . .
hey guys. I am trying to code top down 2d movement in unity 6. I want the player to move with WASD and aim at the mouse. My code seems to work when standing still, however the aiming lags behind or does funky things when moveing or when the mouse is close to the player. I''m also getting terrible performance. Please take a look at the video. Here is my code as well:
https://pastecode.io/s/a9avmq6p
Not seeing anything here that would create performance issues.
id be curious as to what the build version does
Definitely use the profiler to find out what’s causing the lag
hmm, ill build it right now and take a look. will probably take like 30 minutes though
whats that?
do you have something in the editor ?
👇 ..
Analysis**
you'll want to hunt for spikes*
click 'em use the Hiearchy to find anything thats taking considerably more time than the others
Looks like im running out of memory. Could just be that my laptop is very old.
If I want a global variable, what is the recommended way? I dont want to query my gamemanager singleton to get the current game state for example.
it needs to be static. you can use a static class, a static variable on a regular c# or MonoBehaviour class, or an SO . . .
@cosmic dagger Ok that is the best way? Will it survive scene changes? Instead of having a dont destroy monobehaviour in the scene?
just make it static
Static variables will persist when you load a new scene
static variables exist on the class, not the scene or any GameObject. if you have a singleton, you need DDOL. an SO will persist for the entire game session . . .
Hey everyone, I am trying to code a simple 2d top down player movement script. Currently everything is functional but the movement is choppy in the editor and the build. Unfortunately I can't get a good video of it because my computer is too underpowered. Heres the code: https://hastebin.com/share/qevituqubu.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
i'm willing to bet that it's actually your camera's movement that is stuttering rather than the actual movement of the player
although you are breaking the interpolation of your rigidbody each frame
if you have a camera, disable it or deactivate the GameObject. test the game with the player moving to see if it stutters . . .
is there a way i can start the StartGame() method after the timeValue(my 3 second countdown) but only for one frame like in start but obuisly i cant do it in start after 3 sec?
and what would that do?
Or you can keep it as void and start a coroutine from within it
Coroutines are methods that you can execute over a longer period of time
https://docs.unity3d.com/6000.0/Documentation/Manual/coroutines.html
You can wait inside them
so i can wait 3 second okay let me check it out
im stuck i read a liitle about them but i dont know why it isnt working do i need a usnig directive or?
Well, read the error
it seas that i might be missing a using directive and the type or namespace coud not be found
Yeah, use the quick tools in vscode to import the correct namespace
oh i did it
Click IEnumerator and then the bulb/cog icon or whatever
hover over the red line, hit alt+enter, then hit enter
im so dubm
yea i did it just now
i tried it at first but id didnt work idk anyway thanks both
Not sure if this is the final code otherwise, but waiting at the end of the coroutine does nothing here
Because you do nothing after it
yea im still experimenting
got it wait for sec goes before it
and not .3f WAitForSeconds(3)
could someone help me figure out why my UpdateLocationOwnedByIndexValueServerRpc() function does not work when run by a client? am new to using Unity's netcode for gameobjects 🙏
my function is run on a button which is clicked on by the client
it works for the host but not the client
!code
also #archived-networking
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/ , https://paste.ofcode.org/ , https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
thanks
Quite the method name
that's all i was looking at . . .
👍
lol dont worry I know the struggles. This is why I prefer underscore naming convention over camelcasing
also ServerRPC is legacy I think.
It's just RPC with different parameters
what do you mean?
Any process can communicate with any other process by sending a remote procedure call (RPC). As of Netcode for GameObjects version 1.8.0, the Rpc attribute encompasses server to client RPCs, client to server RPCs, and client to client RPCs. The Rpc attribute is session-mode agnostic and can be used in both client-server and distributed authority...
also I forget but you may need to inherit network mono
oh thanks
I have a question that is better asked via example code and its comments (look for PROBLEM AREA comments), so I'll plant those here and if additional information is needed, just let me know!
https://pastebin.com/g8yUhn3N https://pastebin.com/FgVuHLez
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.
Thinking of doing delegates
hello! Im making a flappy bird game and i want the game to display a win screen when the score counter (ui text object) reaches a certain number (27). However, I'm not sure how to write code to make a certain action happen (if score = 27, show win screen) in c#. Could someone help me?
I was following a video tutorial on how to create a measurement tool through scripting and for some reason Unity doesnt let me add the text object into the field and its empty when I click on it. What am I missing?
using TMPro;
public class Measrement : MonoBehaviour{
public GameObject pointA;
public GameObject pointB;
public TMP_Text text;
void Start(){
float distance = Vector3.Distance(pointA.transform.position, pointB.transform.position);
text.text = distance.ToString();}
void Update()
{}}```
That field takes a prefab since you are directly modifying the file presets
Drag the script onto an object in your scene, then drag your text object into that box
I see its working but it has a 0 now nvm had to reassign the objects
Quick tip, you can write text = $"{distance}" which turns it into a string
Another example $"This is {distance} long" to show the text in a practical way
Also by the way printing a float to text will often be 10 characters long as floats can have a lot of decimal places.
$" {distance:F2} " which will only show the first 2 decimal places

hey I need a little guidance, I'm trying to make it so that if I click on a sprite it changes color. I got the color to change on click, but it doesn't matter where I click lol, how do I make it only when it's on the sprite?
well right now you're just calling GetMouseDown every frame, then checking if the mouse button was clicked and if the GameObject you assigned in the inspector has a specific tag. consider using a physics query (like OverlapPoint) or use one of the event system interfaces for detecting clicks IPointerDownHandler
hey guys, i am having some trouble with RaycastAll, with it not detecting any colliders. The player does have a collider and the variable is assigned correctly.
this however does work, but doesent detect anything else besides the player
that is what im trying to fix, it isnt detecting other objects/colliders infront of the player
found them on that one asset store for free, called monster pack or smthn
problem is
raycastall isnt detecting anything
while normal raycast only detects player
yeah, the grid has a tilemap collider while the player has a box collider
the little goblin also has a box collider
that makes a raycast downwards to detect ground right?
oh maybe, let me fix that
alright
nope 😔
oh that worked!
so this is good?
yeah
its for a detection system
whats the *5 do?
doesent the third paramater set the distance already?
lol
btw do you know why this is always detecting as hitting the player?
i see
that will be useful, but the problem is it is always detecting the player
like when it is out of the raycast line
not currently
oh you mean a tag
yeah i have that
ill look into it
okay i got it to work properly with tags 👍🏽 , ill probably use layermask for ground detection
thank you so much
this is just temp assets as i wait for some classmates sprites
im actually about to import some of them rn
they look great
ive tried godot but just couldnt get into it, albiet i was alot less experienced with coding
i think it was because i was still learning basics of c# but most godot tutorials was for g
ill try, thanks 🔥
Can anyone help with build errors please?
#📱┃mobile would be the place to get help building for mobile platforms
This is unnecessary to be clear, directions should be normalized and you already provide the length in the other parameter.
For something like DrawRay, it has no Length parameter so the direction isn't normalized
and it's necessary to scale it to whatever length is relevant
For a raycast to register a hit, the target object just needs to have a collider of sorts correct?
Of course
How hard did I mess up by CTRL+R*2-ing a class name
Why don't all objects have null properties in the Inspector when creating a new project, but when project already created - they have null properties in Inspector?
why doesn't the healthbar of my bunker change?
it can take damage but the bar stays full
you're dividing an integer by another integer. this will result in a whole number . . .
fillAmount is a float: a decimal value. you need to get the result as a float . . .
it still doesn't work even as a float
how did you change it?
change the two int's in both scripts to float
what values are you using? place a log inside of UpdateHealthBar to see what results you get . . .
You only update the healthbar at the start
true, it does not update during runtime, but i thought they were having issues at the start of it . . .
They say it can take damage but bar is still full
Which makes sense if the bar is only updated at the start
So put UpdateHealthBar() inside TakeDamage() if that’s the method you use
good catch. i didn't see the text underneath the photo . . .
Not sure if this is related to UI or code, but I got a problem where my UI elements are never positioned properly in any resolution but one when I'm using a piece of code that make the elements follow the player
This is the code I'm using
https://paste.ofcode.org/eASzuv2sss7TJiyVHTsQs7
The elements are placed in a camera screen space canvas btw
huh?
i missed part of your question. it's because you're not calling the method after taking damage. check out Melton's response's . . .
you need to call the method every time the health changes to update the health bar . . .
doesn't look like it works
No, I’m saying that you put the UpdateHealthbar method in the void start(), which only updates when the object is loaded. Either put it in void Update(), or better yet, in the TakeDamage() method
can you show us the updated code?
it's not going down still
you're decreasing healthBunker and using that as the maxHealth value. wouldn't that be the currentHealth value? i'm not sure why you place the max health before the current health in your parameters . . .
shouldn't you decrease currentHealthBunker instead . . .
Where are you using the TaleDamage method?
ok current health was actually meant to be max health
got mixed up
but i switched them around and it still didn't work
log the fillAmount value . . .
this is after taking damage?
no before
we need after. it should be 1 before because your health is full . . .
but the debug log says object for some reason
not sure what you mean . . .
also, you only need to log HealthbarSprite.fillAmount. matter of fact, just do . . .
Debug.Log($"Percentage: <color=cyan>{HealthbarSprite.fillAmount}</color> | Current: <color=cyan>{currentHealth}</color> | Max: <color=cyan>{maxHealth}</color>");```
did you add in my log and test it after taking damage?
i can't put it in the take damge script since the healthbar is on a seperate script
huh, just place this log in UpdateHealthBar after fillAmount is assigned . . .
yeah it registered the numbers just fine
cool, but this isn't after taking damage. that's the log we're waiting for (to see if it works), not at the start . . .
the bunker health does go down
i see it in the inspector
but the bar remains unaffected
then you need to make sure you referenced the correct health bar . . .
i did
anyone know why my drawline doesent track properly? my actual raycast works fine now, just annoyed that the drawline isnt
in the inspector, set the fillAmount for the sprite to 0. test and see if it fills to 1 (because it's set to 1 at the beginning) . . .
nvm i switched to drawRay and it works 10x better
it does
i set it to 0 and started the game and it became 1
i don't see what isn't working. i haven't seen an updated log where the current health is lower than the max health and the correct percentage is displayed (along with the health bar image from the game) . . .
You're using DrawLine with a position and a direction instead of two positions. Use DrawRay, or fix your logic.
I missed you fixing it, sorry
which hand
which joystick
could you tell us more about your scene, code and how everything is set up
no
send it here
@queen adder
I might not be here all the time, there are others who can help you
👍
Yeah use a paste site for code
Can you rephrase your question? What is the current issue
I’m about to lose my mind! (Beginner here) I'm trying to get data from an InputField, but it doesn't update unless I edit the prefab itself and override it before starting the game. I'm trying to update the value, but nothing seems to work. Can someone please help me figure out what the issue is?
using UnityEngine;
using System.Collections.Generic;
public class ProductUI : MonoBehaviour
{
[SerializeField] private List<ProductData> productData;
public void PurchaseProduct(int indexID)
{
ProductData selectedProduct = productData[indexID];
if (selectedProduct.inputField == null)
{
Debug.LogError("InputField is not assigned in ProductData!");
return;
}
selectedProduct.UpdateInputField();
Vector3 spawnPos = new Vector3(0f, 1f, 0f);
int totalPrice = selectedProduct.buyPrice * selectedProduct.amountToPurchase;
MoneyManager.Instance.SpendMoney(totalPrice);
Debug.Log($"{selectedProduct.name} purchased - {selectedProduct.amountToPurchase} times for ${totalPrice}.");
for (int i = 0; i < selectedProduct.amountToPurchase; i++)
{
Instantiate(selectedProduct.productObject, spawnPos, Quaternion.identity);
}
}
}
using TMPro;
using UnityEngine;
[CreateAssetMenu(fileName = "ProductData", menuName = "ScriptableObjects/ProductData", order = 2)]
public class ProductData : ScriptableObject
{
[Header("Product Data")]
[Tooltip("Index ID for a product: Ensure that there are no duplicate numbers.")]
[SerializeField]public int indexID;
[Tooltip("Product name.")]
[SerializeField]public string productName;
[Tooltip("Product description.")]
[SerializeField]public int productAmount;
[Tooltip("Product purchase price by the player.")]
[SerializeField]public int buyPrice;
[Tooltip("Product sell price to the AI.")]
[SerializeField]public int sellPrice;
[Tooltip("Prefab of the product.")]
[SerializeField]public GameObject productObject;
[Tooltip("InputField of the product.")]
[SerializeField]public TMP_InputField inputField;
[HideInInspector] public int amountToPurchase;
public void UpdateInputField()
{
string inputNumber = inputField.text;
if (int.TryParse(inputNumber, out amountToPurchase) && amountToPurchase >= 1)
{
inputNumber = inputField.text;
amountToPurchase = int.Parse(inputField.text);
}
}
}```
What doesn't work specifically? The code that does the actual updating? What is being updated? inputField?
ok so i have a question on how to format scripts in the editor.
i have this script:
`
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class uiManage : MonoBehaviour
{
//player 1
public Sprite p1Trump;
public Sprite p1Kim;
public Sprite p1Joe;
public Sprite p1Mette;
//player 2
public Sprite p2Trump;
public Sprite p2Kim;
public Sprite p2Joe;
public Sprite p2Mette;
//Canvas
public Image p1Image;
public Image p2Image;
public TextMeshProUGUI p1Name;
public TextMeshProUGUI p2Name;
public void SetP1(Sprite sprite, string name)
{
p1Image.sprite = sprite;
p1Name.text = name;
}
}
`
the only problem is it looks like this in the editor:
is there any way to space certain sections out by a line or two?, or add headers, like in google docs
Yes using attributes you put on the fields
[Header("Sample")]
private int Value1;
[Space(10)]
private int Value2;
thanks alot
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/ , https://paste.ofcode.org/ , https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Ok well 3D movement keeps giving headaches, for some reason when I try to normalize my Vector3 (for movement), It either doesn't work (doesn't normalize it) or it makes all movement (including Gravity) slow and sluggish. https://paste.ofcode.org/x7HEVAHNF6WvkcbwNgv5ws ( In this code nothing is Normalized since I want someone to tell me WHAT to normalize)
when you normalize it, max values become 1
so by setting your velocity to your totalmovement variable, you basically clamp the velocity to 1
why arent you using something like AddForce? does the movement need to be stiff?
Well in the past Velocity was used for movement, but Unity then decided that it would be fun to mix it all up. I did try making it with force myself but I had no idea what I was doing, also, this is not a physics based game ( I dont know what do you mean by stiff specifically)
FYI, this line transform.rotation = ...
breaks your rigidbody's interpolation because you are directly modifying transform
If you even have interpolation enabled (you should, it smooths the difference of rendering vs. physics updates)
I do.
addForce is just: velocity += force
Start with changing from GetAxis to GetAxisRaw
GetAxis has some smoothing applied to it by default
GetAxisRaw bypasses that
I think that is a good thing?
Makes customizing movement easier?
Idk, you are mentioning stuff like "sluggish" so now i am confused what your problem is
You said something about "breaking interpolation", I should look into that?
Yeah, use rigidbody.MoveRotation instead of modifying transform.rotation directly
Modifying a transform when it has a rigidbody is bad. The physics system doesn't get properly notified about the change so it leads into bad collisions, broken interpolation and other glitchy stuff
When interpolation is not working, your character movement usually appears jittery
Well that requires a Quaternion... I dont have a quaternion xD
So rotation values in Transform are a quaternion?
Yes. You can easily check if you just hover over rotation in your IDE:
Or when typing it
Yeah I got it, thanks, I guess that helps, but I still can't normalize Dx
Normalize what?
For some reason when I try to normalize my Vector3 (for movement), It either doesn't work (doesn't normalize it) or it makes all movement (including Gravity) slow and sluggish.
Is using scriptable objects for making enemies with stats system a good approach?
Sounds like you are normalizing a vector that includes your Y velocity
You don't want to do that
Normalizing a vector sets its magnitude to exactly 1. Do you actually want to do that?
In any case you should show the code that you tried
Yeah, how do I separate it?
Do you want to normalize it or just limit your speed?
ScriptableObject assets are a nice way to re-use data that many different things need to reference
https://paste.ofcode.org/NEt7UbmckqJNQB6d9A3DDP arent those basically the same things? All I want is for the player to not go faster when they are moving diagonally
They are not the same things. If your movement vector has a length of 0.5, normalizing makes it length of 1.0
Limiting it would only make it 1.0 if it is over 1.0
Like Vector3.ClampMagnitude
I want to make like a stats system for my player and for the enemies too but I have no idea how to approach this
yeah, so there are two unrelated problems with your code here
- You are mixing together player input and other sources of velocity
- You are normalizing player input, which will make things like joystick input misbehave
You wanna do something like cs totalMovement = transform.TransformDirection(inputX * moveSpeed, 0, inputZ * moveSpeed); totalMovement = Vector3.ClampMagnitude(totalMovement, 1);
Then in fixedupdate...cs rigidbody.linearVelocity = new Vector3(totalMovement.x, rigidbody.linearVelocity.y, totalMovement.z);
I keep fussing with this
tbh, just start with a dumb bag of stats
give everyone a Stats object
Keep the y velocity out of the equation when you limit the move dir
[System.Serializable]
public class Stats {
public int strength;
public int dexterity;
}
e.g.
Ok thx I will try all those things
aha and this works just fine?
Ok so I copy pasted the code in and well, gravity works fine now, but the movement is incredibly slow (probably because totalMovement is limited to 1)
Does every entity in your game have the same set of stats? Can you gain new kinds of stats over time?
That would require something more complex
well not entities
but like the player will hava a set of stats and enemies a different set of stats
osmal's example has one thing backwards
you should multiply moveSpeed in after clamping the magnitude of the input vector
If you want it to go faster you should just multiply totalMovement with some speed float after you clamped it.
Oh ffs, I didnt even notice the whole moveSpeed float
Also, if diagonal movement is still faster after fixing this, that implies that the individual axes are giving you values smaller than 1
e.g. you're getting only 0.5 when you hold the D key
Wait, im gonna do more testing
I wouldn't expect that to happen
So fix the formula first. Consider logging the individual axis inputs as well as the combined vector.
That'll make it very clear if something is wrong
how can i make a set of stats for the player and another set of stats for enemies?
Do you mean that the player will have stats that enemies don't, and vice-versa?
yes
there are a couple of ways to do that
one would to give everyone the same set of stats, and to ignore anything that's 0
You could create two different classes for the two kinds of stat blocks, but that would result in a lot of duplicate work
since you'd need to write code to handle attacking a player vs. attacking an enemy
That's a big reason I prefer to make everyone "equal" nowadays. I don't have a Player class and a Monster class; I just have an Entity class
so basically apply one of these to everyone and just use what I need on each entity?
would this work?
Ok well thank you for helping me guys!!! this movement looks very stiff, so I will look into "addForce" but Im 90% that its gonna be way too floppy.
!docs
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Yo idk if this is code but my camera wont work in unity for some reason
guy can you help me?
so basically I wanted to make the player gun stop shooting when player died. But the thing is it on the other script; so i use the bulletSpawner = GameObject.FindGameObjectWithTag("Spawner").GetComponent<BulletSpawner>(); on the player script, to find a way to make these two script commutate with each other. After that i make a bool one for player private bool gunCheckList = true; and aother for the gun public bool gunCanShoot = true;. Then on player script void update i put this code in if (gunCheckList == false) { bulletSpawner.gunCanShoot = false; } which will disable the gun form shooting after player death, But instead i got an error, a Null error on line 40 which is bulletSpawner.gunCanShoot = false;.It say "NullReferenceException: Object reference not set to an instance of an object
CubeBeActing.Update () (at Assets/script/CubeBeActing.cs:40)''. what should i do?
which basically means that this line
bulletSpawner = GameObject.FindGameObjectWithTag("Spawner").GetComponent<BulletSpawner>();
is not working and by a series of simple logical deduction it means the Spawner object found does not have a BulletSpawner component
maybe because on the Gun since i only give the Spawner tag for the gun head which is parented by empty gameObject gun, and not the whole thing
I need help with splines
If you aren't finding the object that has a BulletSpawner on it, then this code won't work
I would suggest storing a reference directly to the BulletSpawner
If the player only ever has one gun, this is trivial
yes only a single gun
Does anyone know how to make an object Accelorate and decelerate on a spline and to be able to control it?
Sounds like you want to store a "spline position" value
i.e. how far along the spline you are
You can use that to calculate a world position
And would that do what i want it
Any tutorials out there that can help me
Or could you?
There are two SplineContainer methods that you'll want to use
alr?
CalculateLength, which tells you how long a spline is in meters
EvaluatePosition, which tells you the world position at a certain percentage along a spline
Imagine the spline is 20 meters long and you want to position yourself 5 meters along the spline
5 / 20 = 0.25
Pass that to EvaluatePosition to get a position
If you move one meter forward, now you get 6 / 20 = 0.3
So this is a lot like moving in just one direction, back and forth
but you use the spline to turn that into a more complicated shape
Also, if you need to rotate the player, you can ask the spline for a tangent vector (pointing along the spline) and an up vector (pointing out of the spline)
That's enough information to figure out how to position and rotate something
how to use this?
check where ur camera physically is and also your set resolution on game tab
hes saying just to have a separate script that holds their value
basically saying that ur question is simple
and like how do I apply the stats to the player and to the enemies?
if stats are just integers
need more info
like whats the stats and game
stats are like health, maxhealth , range etc
it mostly just be math depending on what ur doing
changing health would change the healthbar scale and u die when it hits 0
buy how do i make the player has its on stats and each enemy to have its own stats
ah
make a script that every enemy and player has
if these stats are shared by enemies
then u can change the values of each stat on each prefab however u want
ok so just make a script that adds stats on the prefab then each enemie when spawned will have the stats
and the player too
more like make a script with stats that are all 0
then change the stats for each enemy type and player
but yea if thats what u meant
what
i made this
[System.Serializable]
public class Stats
{
public int health = 0;
public int maxHealth = 0;
public float rang = 0;
public float runSpeed = 0;
}
you dont need to = 0 and you dont need the system.serializable
looks good other than that
now in the player prefab I add a script with monobehavior and how do I reference this?
ofc
i tried this
public class PlayerStatsHandler : MonoBehaviour
{
public Stats stats;
private void Awake()
{
Debug.Log(stats.health);
}
}
and it gives me this error
NullReferenceException: Object reference not set to an instance of an object
PlayerStatsHandler.Awake () (at Assets/Scripts/Player/PlayerStatsHandler.cs:8)
i dont understand why
yes, stats is null, you do not initialize it
so if i say stats.health = 100; will it work?
yes, but it is not
public class Stats
{
public int health;
public int maxHealth;
public float range;
public float runSpeed;
}
he was told to remove that
this is stats
yea by me cause i wouldve just had the script on each prefab
just easier
then you should have told him to inherit from MonoBehaviour
o lol true didnt notice that
so what
u see how it has the monobehaviour at the top
u just need to do that for other script
yea
then attach it to your prefab or player then fill the Stats variable on the player script
ight
but like what is the use of making it like this ?
without monobehavior?
yes
its nice for things that are static for example game data. You can check if the player has beaten a certain enemy from any script
but the stats are different for different things so u would need to make a new stats in the script every time if u didnt have monobehavior
so this way is easier i think personally
yes this is easier
also i dmd
anyone could teach me how to make a player sprint script where the sprint eases into the max speed instead of reaching the max speed instantly, thanks
Look up the docs on Lerp
or Mathf.MoveTowards, perhaps, if you want to steadily approach a target value
i see thank you guys
I have been trying to set up VSCode with Unity for nearly the whole day and the "C# Dev Kit" extension has a little popup saying "The active document is not part of the open workspace. Not all language features will be available." where it prompts me to insert a solution. Except unity doesn't use a traditional solution (like .sln and .csproj) and I can't simply open the file and get Unity stuff because Unity depends on the C# Dev Kit extension. How can I make the Unity extension working without needing a solution file?
you are wrong, Unity does use standard .sln and .csproj files
where can I find them?
in your project folder
no .sln or .csproj in sight
don't know which app you are using to display that but I can assure you they are there
on windows the default code editor is VS, right?
yes, but the folder setup and contents are identical on all platforms
then how do I not have the .sln file
only you can answer that one
I will create a new project just to see if you're right
Maybe use a different file manager
They're both representing the same damn files
I can use the Dolphin file manager if that's that much of an issue
I use Nautilus for Linux OS's
brand new Unity Project
So that looks like it is only showing folders not folders and files
false, here's the Assets folder
You got the visual studio editor package installed?
visual studio doesn't have a linux port
visual studio code does
In Unity the Visual Studio package is used for both
I think the package generates those files
the VS Code package is depreciated
Package Manager and WHY IN GODS NAME are you using 6.1. Alpha if you don't know what you are doing
6.0 stable doesn't work on linux
and I dont want to use an outdated version
6.0 does work on Linux, there are thousands using it
it doesn't for me but that's a seperate issue
where do I see the package manager window
thank you
Be warned, extremely experienced Unity devs only use Alpha release when dragged screaming and kicking to do so, On Linux even more so
I had it installed since project creation
And its selected in external tools and you hit regenerate?
in external tools I only have the option to browse for the text and/or image editor
which I did browse for VSCode
I think I might have an idea
I think I might know what's going on
yes, these are the options in the dropdown
So it's not finding your vscode?
why does it only generate the .csproj when using VSCode
can't it just generate them during project creation so there is no confusion
I was using a modified version of VSCode which it couldn't detect, a quick install of the actual VSCode and it works and I can generate the .csproj
already solved it, unity couldnt find the modified VSCode
Thank you so much for helping me with this
It created the solution file?
the .csproj but I think it works
will check when the extensions decide to cooperate
I think you can also try Assets > Open C# Project
it works
Okay nice
Thank you so much, I thought my VSCode extensions were wrong or sum.
Is it possible to generate the csproj file without the default text editor being VSCode?
Donno
How many times should I regenerate my .csproj files?
Prob once
Then I can just change the editor after generating it, thank you again and I think I will head out
Unity creates multiple csproj files I think when you install packages and what not, because I have like 5+
hi y'all, how do I set the position of a cube in Unity? I tried to use this: targetObjCoord.x = (float)X1t;
targetObjCoord.z = (float)Z1t;
but it would not work
(I want to set the x and z coordinates to X1t and Z1t
You have to set the position of the object's Transform.
theObject.transform.position = whatever;```
thanks!
so for example could I do theObject.transform.position.x = whatever; for each coordinate? or do I have to create a vector first ?
that won't work no
you should make a vector
and assign it
ok thanks
yea unity doesnt allow this for some reason u need to do the full transform.position = new Vector3(x,y,z)
Does anyone know why my audiosource is behaving like this?
I need a hand with raycasting issue.
I've placed 2 cameras, 1 is main for player, 2nd is it's child, in attempt to fix the issue i have with the test.
Before applying a canvas to make the project look more pixelated i was able to click anywhere on the surface and my green bean would gladly walk there. Now all I get is just that raycast did not hit the ground. I've no idea what to do.
It is generally a blank project so if anyone needs i can just upload entire project
Hello! I tried many method to set the parent of an Instance but 0 success.. Someone can explain me why this:
gameObject = UnityEngine.Object.Instantiate(weaponPrefab, new Vector2(0, 0), Quaternion.identity);
gameObject.parent.transform = character.transform;
Is not working please ^^ ? (I tried with parent, with gameObject.GetComponent etc.. But nothing works :/
You’re setting the transform, not the parent
yeah u dont need the new Vector2
replace with a gameobject
Read your error message
I read on a blog "Because the GameObject does not know anything about parenting. That’s the Transform’s job." ^^
transform.parent = newParent;
And then you proceeded to write the wrong code
idk where u read that lol
transform doesnt have to do with parenting
i mean not setting it
yes but you’re setting transform equal to another, read praetor’s message where you do transform.parent
you should look at the code examples there and follow them. What you wrote is nonsense.
any ideas?
Without sharing your code how should we know?
Object reference not set to an instance of an object
With:
gameObject = UnityEngine.Object.Instantiate(weaponPrefab, character.transform, Quaternion.identity);
gameObject.transform.parent = character.transform;
Is this wrong then ?
on which line
should u be using gameObject as a variable name?
also pretty sure that code wouldn't even compile
not a good idea, no
gameObject = UnityEngine.Object.Instantiate(weaponPrefab, new Vector2(0, 0), Quaternion.identity);
gameObject.transform.parent = player.gameManager.Character.transform;
Error on the second line ^^
When I manually add the prefab of the audiosource onto the scene, it plays sound without any issue. It's only when I instantiate the prefab through a script the audio clip can't run properly. I tried to recreate the prefab instantiation setup in a new project and it worked just fine.
player or player.gameManager or player.gameManager.Character one of these things is null
figure out which one
and fix it
^ player move, isometric camera setting, and movement with left click
IDK tho how that is related to raycast which is a togglable in canvas
Since you're using Camera.main, make sure you only have one camera tagged MainCamera and that it's the correct one.
Your code is doing the raycast
the canvas is not relevant
Raycast Target is what i think ur thinkin of about the canvas
I have Main Camera, it has child objects RaycastCamera, and within it, Camera.
I get mostly did not hit ground, only in very lower part of the display screen, it manages to make occasional hits but then the bean is not going where its supposed to at all
Which one is the main one
is it the correct one
what are the tags of the two cameras
why are there two cameras
Omg ty! It was an error before this action, the gameManager was not created!!
If I understand "Object reference not set to an instance of an object" == somethig here is Null/Undefined ?
yeap
it means you did something.someotherthing and something was null
MainCamera is the main one
I have a canvas with a texture, it ended up blocking completely my movement so i made 2nd camera as a child, with disabled camera feature, to only do the culling
exactly.. and the errors can be a bit vague. it normally hits the correct line
but sometimes it can be the line after
the canvas cannot block the movement since you are doing Physics.Raycast.
The canvas would only block the movement if you are using the event system for the click handling, which you don't appear to be doing.
Ty boys for ur help ❤️
I do have clicking script in eventsystem object
You seem to have three different handlers for click to move then
so it's really not clear which one is the "real" one
But that third one would be the one that's affected by a canvas
so you need to be more specific about which specific script is not working and what's going wrong with it.
You also should clean up your project and get rid of unused scripts which are probably causing confusion
For now I have:
- Deleted the 2nd camera so I only have 1
- From the EventSystem I have removed the script responsible for movement
Now half of screen works but bean always travels to the right and never stops
Continue debugging your code.
You have PlayerMovement and SimpleClickToMove scripts still. Why still two movement scripts?
Also the SimpleClickToMove you put on the EventSystem GameObject? I suspect you are not actually using that script.
I don't understand why it isn't working
You'd have to show your code and explain what it's supposed to be doing.
ye that is already removed, i only got 1, issue persists
i only have 2 scripts in my project, 1 for isometric view, 1 for movement
I don't think it really matters in this case, because I only have an Instantiate function for the prefab
i dont understand why the character only responds to click when i click lower half of the display, but never when i click the higher half. And why it only travels in one direction (right) and never anything else.
And when I remove the Canvas, it magically works as intended.
Have you started debugging your code yet to find out?
Then what is playing the sound?
The code seems to work, issue only occurs when I have the canvas, and when in main camera i use output texture for it
The audiosource component
Right - which is why you need to start debugging the code in those circumstances.
with Play On Awake? There's no scripts on the prefab?
What else is on the prefab
Just a light source and a model mesh
Show the inspector? Make sure it's the actual prefab and not an instance in the scene
Also make sure your console window is always open in Unity (it wasn't in your video) so you can see any errors or warnings.
Earlier I tried to make my map generation script play the audio clip manually after instantiation but it still gave the same result
There were no warnings relating to audio sadly
Just this
Took a look at the profiler and there doesn't seem to be any issues there either
What's weird is that whenever the game window is unfocused, the sound starts playing normally
This led me to conclude that, for whatever reason, something is resetting the audio clip's playback after each frame
ended up scrapping this render and it works
back to normal boring display
Nothing seems out of the ordinary to me here
Im gonna start attempting to make a pathfinding algorithm, and i was wondering if there was any way to use raycast to find where it stops touching something
Like if it started in a collider with the ground tag
Thenpoint where it is no longer touching that
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Oh wait
I might've actually discovered something
So apparently, SetActive is being run on every map chunk, every frame
That's what's causing the audio to repeat
This was such a stupidly easy fix
I have a quick question someone might have an answer to.
I was working on my project and decided to connect to unity version control, it appeared to work, but I didn't push any changes.
My unity project closed and I could not open it anymore. After, the project folder is missing all assets and the scripts were all removed.
No my code editor shows this kind of thing:
I tried to download the project via the version control and it is empty with no assets. Is the project recoverable? Has anyone seen this before?
hey guys
my script have a problem, i make a level platformer game
the player needs get a key to open a door
and his game to find the key u need go in secrets passes
and when u touch in the secret pass the level show this
and when u have the key u can open the door and go to the next level using a teleport, the variable detect teleport is HasTeleported, and the wrong script is ResetVar, this reset all variables to need teleport, open secrets passes and more. And when I go to Level 4 the variable isCollidingWithPlayer responsible for detect if player find the secret pass doesnt working and stay to True(isCollidingWithPlayer are a bool)
Looks like you're calling roomParent.SetActive(visible); every frame
Which will probably restart the audio
seems like a bad idea to deactivate and reactivate the rooms every frame
I decided to change the instantiation parent to worldGrid
So nothing gets deactivated
That's just to make sure only chunks near the player are active
Albeit the implementation is a bit dodgy
I mean, I don't know what the intention of that code is but what it's doing is deactivating and reactivating every room every frame as far as I can tell
Yeah
it wrote in what you wrote, preatorblue.
I've been making a game that has very large numbers. What is the best method to keep transforming all numbers in a shorter form so that c# can do calculations?
You need to use a library like https://github.com/Razenpok/BreakInfinity.cs
gotcha, thanks
could someone help? i just wanted to do game for my friends
is this okay code? or will this create too many instances for the garbage collector?
What does "too many instances for the garbage collector" mean?
yk like when u make "new" , you make a new reservated place in the ram
The garbage collector comes into play only when you stop referencing an object you created. Are you doing this every frame or something?
nah only when player changes level settings
then it's fine
okay
what is this
hv i not seen this screen in unity
Yo I'm building a game and I add y axis movement and for some reason when I look up it moves me forwards and when I look down backwards
https://pastebin.com/BLtM8QXM it doesnt increment the fov by 10 for some reason, the script is in the main camera object
My character keeps falling through the floor that I placed in game. I added the collider but nothing is working
wdym? cant help without code and do you mean when you move the mouse it moves your char
post the inspector of object with the collider and the inspector of the character
log inside the if statement to make sure its executing
it doesn't execute
When I move up, it moves the camera
so there u go lol
make sure it has the right tag
it has
brother post code clearly thats the issue
post the whole inspector of that object
here's the code
first 2 are the cam changer part and third pic is camera object
wdym it moves u forward and backward?
its just the y camera movement?
it moves ur character forward
what game is this where the mouse controls the characters
but u said it moves the character
Yeah bc it moves me forward and backwards, but its unwanted
uh does the player collider with other things normally?
yeah now that i think about it i maybe shouldve done this in the player collision script and not the camera script
imma try and see if it works
why is ur character movement connected to ur mouse movement
It is?
is ur movement variable for the camera or player?
whats perplexity
so ur gonna hv ai and #💻┃code-beginner make ur game for u
ur good
I tried following the tutorial and didn't understand a single thing so I just decided to use AI
so the rigidbody is the camera?…
Yes
Not a bad idea
yea it is..
because it will take longer if u finish at all and u wont learn
so back at square one with no experience even if u succeed
Fair point
lol yes
maybe
yep it works now haha, thanks for trying to help me though, appreciate it!
i like cant trust u lol
ur saying this script is on ur camera
im still confused
It is
ur movement variable is depending on ur mouse movement