#💻┃code-beginner
1 messages · Page 238 of 1
you could absolutely shove a big blob of JSON into PlayerPrefs
but i don't like finding 50kb of json in the windows registry
idk whats wrong but, when i set static instance it awake, its always null, but when i set it in start, its not null, aby way to fix that?
code
it working in start just tells me it's dependent on something else being executed first.
Hi, I've been following a tutorial to make a game.project for my college course, and I've run into an error: assets/scripts/inputmanager.cs(18,54):error cs1061: Playermotor does not contain a definition for Jump, and no accessible extension method Jump accepting a first argument of type Playermotor could be found.
https://youtu.be/rJqP5EesxLk?si=-3M2mSG9rJhXHeoR
The first video in a series where we are creating a First Person game!
In this video we look at setting up our characters movement.
I've setup a Discord!!! and I would love to have you help me start up a friendly community where we can all help each other grow as game developers!
Discord invite link:
https://discord.gg/xgKpxhEyzZ
Can't wait t...
This is the tutorial I have been following, I'll be sending the code if asked
!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.
Can I send the files or do you want ibe if those above
part of code that gives error:
hiScoreText.text = "Hi-Score: " + SaveValues.instance.currentGameData.score.ToString();
You sure it's not currentGameData
debug all parts of what's you're accessing one by one
Am I allowed to send my .cs files
but otherwise the script there seems fine
check the links from the bot in the above messages . . .
I didnt changed anything, but seems to work... its only null in first frame now
is hiScoreText in a script that's also using awake?
LateUpdate()
it was on Update, but nothing changed
Right, but is the script being initialized with Awake()
oh you're calling it in LateUpdate
I see
Yeah, that should only be called after Start so the execution should be fine
Unless you're instantiating these things on different frames.
what "that"? it just doesnt set text any more
if (SaveValues.instance != null) hiScoreText.text = "Hi-Score: " + SaveValues.instance.currentGameData.score.ToString();
It gives me same error... WHY?
because currentGameData is null
oh....
Which mao mentioned up here
dammit..
lemme check
yes you were right
yeah i got what was problem
In SaveData it return null data if file doesnt exist, so, thats why it was null
Sorry for being a bit dumb
Vector3 dampingFactor2 = new Vector3(
Mathf.Max(0, 1 - Damping2 * Time.fixedDeltaTime),
Mathf.Max(0, 1 - Damping2 * Time.fixedDeltaTime),
Mathf.Max(0, 1 - Damping2 * Time.fixedDeltaTime)
);
Quaternion CamDir = cameraTransform.transform.rotation;
Quaternion gunDir = gameObject.transform.rotation;
Vector3 acceleration2 = (((CamDir.eulerAngles - gunDir.eulerAngles) * Stiffness2) - Vector3.Scale(currentVelocity2, dampingFactor2)) * Time.fixedDeltaTime;
currentVelocity2 = Vector3.Scale(currentVelocity2, dampingFactor2) + acceleration2;
currentPos2 += currentVelocity2 * Time.fixedDeltaTime;
gameObject.transform.eulerAngles = currentPos2;
any ideass how to fix this?
I have a problem, in unityhub i dont have sounds but when i make a apk for my phone and then i startet, i have sound like wtf
UnityHub doesn't play sounds, for one thing
If you're talking about the Unity editor, make sure your game view isn't muted at the top.
Wait.. it does sound while compiling? I want to try... Runs to computer
guys whats the use of vector4??
im making ladder movement, why is this not making the player go up or down?```cs
float input = Input.GetAxisRaw("Vertical");
float yTargetVelocity = input * ladderSpeed;
float ySmoothVelocity = Mathf.Lerp(rb.velocity.y, yTargetVelocity, ladderAcceleration * Time.deltaTime);
rb.velocity = new Vector3(rb.velocity.x, ySmoothVelocity, rb.velocity.z);```
!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.
it's another way to represent an RGBA color
oh ok
4-vectors are also used when doing perspective calculations
the rigidbody is kinematic
https://paste.myst.rs/axxiv41w
it actually went like this
moving distance = Swipe distance / Playerprefs get int speed
but it broke through walls so i used rigidbody
but now it should be proportion to squared of the swiping distance.
but the swiping distance is differnt from transform coordinates and we cant move a object as
a specific transform x sturds with adforce
a powerful website for storing and sharing text and code snippets. completely free and open source.
can anyone help me with this?
why is this sending my player flying at masive speed```cs
float input = Input.GetAxisRaw("Vertical");
float yTargetVelocity = input * ladderSpeed;
float ySmoothVelocity = Mathf.Lerp(transform.position.y, yTargetVelocity, ladderAcceleration * Time.deltaTime);
transform.position = new Vector3(transform.position.x, transform.position.y + ySmoothVelocity, transform.position.z);```
ladderSpeed = 1;
ladderAcceleration = 15;
Mathf.Lerp(transform.position.y, yTargetVelocity, ladderAcceleration * Time.deltaTime);
because this is nutty
Hello, I would like to know how I can create an GameObject
that follows a MonoBehaviour to enable animations, transformation etc..
while getting the properties, type and methods from my abstract class Equipement to stock them in an inventory?
Is Equipment a MonoBehaviour already?
If so you don't need to write MonoBehaviour here
It is not
guys can anyone tell me like how much time it takes to switch platform from windows to android?
if Equipment is NOT a MonoBehaviour then this doesn't make sense
then it's pointless
you can't inherit from two things. What you should do is make a MonoBehaviour class that HAS an equipment field on it
i am trying it...... its almost 20 mins and its 50 percent
How can i change this:
doors.transform.Rotate(0f, 0f, -60f);
to more smooth way?
I tried Mathf, i tried lerp, i tried rotatetowards but its very buggy.
Depends where you're calling it
if it's in Update you need to multiply by Time.deltaTime
calculate a target rotation and then use RotateTowards to smoothly move towards it
I wan't to change a prefab variable from code in editor. Problem is, it does get changed but it doesn't gets serialized. Ex: You changed a scene prefab's variable named "position" in the editor from code. Now if you undo or play the game, it will reset itself.
I am using PrefabUtility.RecordPrefabInstancePropertyModifications(this); for when i change a variable in editor and want to serialize it without registering to undo. Is it necessary to do this every time or is there a way to do this automatically?
Hmmmm.
For my game, only Weapon have animations and get gameObjects.
The others class that inherit Equipement will not have such animations. (such as Torso, Helmet...)
Is MonoBehaviour on Equipement still a good choice? (for performance reaons etc...)
I think inheritance is a mistake here
use composition
😮
Weapon : Equpiment -> weapon has animations etc
Equipment : MonoBehaviour -> core of every equpiment
what's the issue
For my game, only Weapon have animations and get gameObjects.
The others class that inherit Equipement will not have such animations. (such as Torso, Helmet...)
how do i do it then
i cant change the velocity
because the rigidbody is kinematic
whya re you using the position as if it means velocity
because i was trying to do it through velocity before
you need to track the current velocity
in a variable
using the position as a velocity means if your object is 100 meters above the ground it will now move up at 100 m/s
so the higher it goes, the faster up it goes
hence it flying off right now
Example :
Torso : Equipment -> does not have animations, will only be used for its Methods/Fields/Property inherited from Equipement.
Basically I'm afraid that by giving it a MonoBehaviour, I must give him a GameObject, defining update() that doesn't have anything and costing performance on the game
wouldnt this work?```cs
float input = Input.GetAxisRaw("Vertical");
float yTargetVelocity = input * ladderSpeed;
float ySmoothVelocity = Mathf.Lerp(rb.velocity.y, yTargetVelocity, ladderAcceleration * Time.deltaTime);
transform.position = new Vector3(transform.position.x, transform.position.y + ySmoothVelocity, transform.position.z);```
in the ySmoothVelocity i changed it to rb.velocity.y
with doors.transform.Rotate(0f, 0f, -60f); its working but not smoothly.
with doors.transform.Rotate(0f, 0f, -60f * Time.deltaTime); its only rotating by ~~ 0.84f, not 60f
no - see this is why inheritance is silly. Don't inherit. Make a prefab with the components you need or don't need. If it needs animation, you attach an Animator. If it is an equipment, attach an Equipment component
Yeah sounds like you're only calling this one time
Rotate is instantaneous
it happens immediately when you call it
if you want something to happen over time, you need to spread it out over many frames
that means doing something in Update or in a coroutine
I see, that's a harsh reality for POO enjoyer
OOP you mean lol?
And for the component, if my Weapon inherit MonoBehaviour, but has a Component Equipement.
Can I still use the Equipment's method ?
oh right
you get a reference to the Equipment component, then you can do whatever you want with it.
Yeah, I'll do the component way. Thanks for the advice
public enum BooleanInputState
{
Low,
High,
NewLow,
NewHigh
}
BooleanInputState State;
// is there a way to simplify this:
if(State == BooleanInputState.High || State == BooleanInputState.NewHigh){ }
// to this
if(State){ }
And conversely, the other two enum states returning false
Maybe if you do this (note I rearranged the enum order)
public enum BooleanInputState
{
Low,
NewLow,
High,
NewHigh
}
bool IsHigh(BooleanInputState state) => state >= BooleanInputState.High;
is that what you are asking? not really sure
You can't put methods or implicit operators on enums, no
I think this is what I didn't know how to ask. Thanks
it's a bit annoying!
But Praetor I will make use of your solution, thanks for that
you can write extensions too:
public static class BooleanInputStateExtensions {
public static bool IsHigh(this BooleanInputState state) {
...
}
}```
Then you can write `if (myState.IsHigh())` @wind raptor
Ah, you can! I was just checking that
with this great code
public enum Huh
{
What
}
public static class Maybe
{
public static bool Test(this Huh value)
{
return true;
}
}
sorry, is myState the enum or the class..?
it's a variable of the type BooleanInputState
e.g. BooleanInputState myState
You don't directly use BooleanInputStateExtensions at all
... Right, ok, and how can i void it once in update?
Now i tried something and doors are spinning, i need to start from other void (void Interact i wrote) and end in update
Extension methods allow you to tack new methods onto existing types.
how can i void it once in update
I have no idea what this means
void means "this method doesn't return anything". It's the return type of the method
Should old code tutorials still be relevant?
General rule of thumb: If it's not related to render pipelines, networking, or post-processing, it probably hasn't changed in like ten years
Ok good
I want to start in other void, void interact that checking if doors are open or not etc
And call one time update to rotate smoothly
again, there's no such thing as "a void"
you have a method that returns void
If you want to run something that takes multiple frames to complete, like slowly rotating an object, you should use a coroutine.
ok i will try coroutine
You either:
- start a coroutine
- do the movement in Update
- look into Tween libraries such as DOTWeen
DOTween honestly is what you want
but you have to learn it
code
interactObj.Interact();
and in script from doors i want to call void update from void Interact
ive also heard of leantween, i wonder which one is better
why do you want to call the Update method? the point of Update is to be called once per frame
i want to rotate smoothly doors
why does the movement speed in the editor not change with the movementspeed in the script even after saving the script? complete beginner in unity
The field initializer is only used when you create a new instance of the component or reset it in the inspector.
DOTWeen has a more elegant interface, I think LeanTween might have better performance.
Anything that shows up in the inspector is a serialized property. Unity remembers the values and restores them as it sets up the component.
So new instances of PipeMoveScript will have a value of 5 for Movement Speed, by default
It serializes that value. If you then change the field initializer so that the default is 10, nothing happens to existing components.
Okay, so use a coroutine.
A coroutine lets you run code across several frames
so you can rotate the door by a little bit each frame
yes yes i will try thank u
alternatively, use DOTween or LeanTween, as Praetor suggested
they'll handle it for you
so if i want to change the speed in the editor with the speed in the script i have to rename the float in the script?
with those, you can just run one method and then let the tween package do it for you
If you don't want to see Movement Speed in the inspector, make the field private
this makes it non-serialized, so unity will no longer remember the value
since it doesn't remember the value, you'll just get whatever the field initializer sets the field to (5, in this case)
so after set the float to private the speed is = to the value i give it in the script?
Yes, because Unity won't be serializing that field, so it won't remember a value for each instance of the component
If that's what you want, then do that
If you want to be able to customize the movement speed in the inspector, then you need to serialize the field
hmm if i want to see the speed in the editor and edit it in the editros as well tho, is there not a way to make the speed in the editor change with the speed in the sript or reversed?
No, because how would it simultaneously:
- Remember a value
- Not remember a value
Now, if the script changes the value of the field in a method, that'll show up in the inspector
void Update() {
movementSpeed += Time.deltaTime * 0.1f;
}
this will slowly increase the value of movementSpeed, and you'll see the value changing in the inspector
ok thanks for the whole explanation appreciate it
im having a bit of a problem rn with the normal mode of the grappler , sometimes when yk im grappling , the rope after getting destroyed , it still seems to be there since it doesnt really let me walk after within grapplers maxDistance and im not sure how to fix it
heres the grappling hook script if needed:https://paste.ofcode.org/Mhc3LaRubQ6krGXKcNujqX
i really dont know why the rope is still there if it gets destroyed. if anyone knows why this is happening then i would love to know the solution!
Also, if you just want to get rid of the values you set in the inspector, right click on the component and click "Reset"
This will delete all of the saved values and reset them to whatever the script initializes them to
i made coroutine but its still working on one frame only
its opening doors but not smoothly
show code
{
if (e4statistics.lfdoorsOpen == false)
{
StartCoroutine(OpenDoors(true));
e4statistics.lfdoorsOpen = true;```
``` IEnumerator OpenDoors(bool state)
{
if(state == true)
{
for (float dAngle = 0f; dAngle <= 60f; dAngle += 1f)
{
doors.transform.Rotate(0f, 0f, dAngle);
}
}```
your coroutine has no yields in it
it's all going to happen instantly
i have yield return null; on end, what i should use instead
that doesn't do anything
you have to put the yield where you want to wait
if you want to wait one frame for each iteration of the loop, the yield needs to go in the loop
it's not magic, the code runs in order, line by line
Think about what your code is doing
yield return null; means "wait one frame"
should i put it in for?
This wouldn't even compile your coroutine has no yield
do you want to wait some time in each iteration of the loop?
You should put the code in that you want to write
also Rotate is additive
so... this thing you're doing is kinda crazy
you're doing +1, then +2, then +3
so the result will be 1, 3, 6
it's accelerating
how should it look then
Also what's the point of the state variable. If you pass in false the function simply does not run, so if you'd ever want to pass in a false, just don't call the method instead
i want to make if(state == false) to close doors
but now im fighting with opening doors
Okay, so it's currently unused but won't be in the future, gotcha
it almost works but doors are f... accelerating lmao
So stop increasing the rotation amount
if state == true
open doors
if state == false
close doors
Honestly the easiest thing for you like I said will be to use a tween lib:
https://dotween.demigiant.com/documentation.php#:~:text=Rotate-,DORotate(Vector3 to%2C float duration%2C RotateMode mode),-Rotates the target
fixed it by doing this 
but i want to use this coroutine since i started
how do i make this raycast ignore triggers?
so they arent optional
They are optional
You just have to actually use the syntax right
that's why I linked to the syntax for it
bruh it works with
{
doors.transform.Rotate(0f, 0f, 1f);
yield return null;
}```
really bro? lmao
Why is your for loop indexer a float
You put an equals sign inside...
if(Physics.Raycast(ray, out hit, queryTriggerInteraction:QueryTriggerInteraction.Ignore))
i wrote it fast only to try if its works
this should work then
but it doesnt
im just keeping it as this
Hi, I'm trying to implement a state machine. The problem is that my character can move and shoot at the same time, which is an issue because a state machine can only have 1 current state.
Then either one or both of those shouldn't be states, or you should add in a "ShootMove" state
I'd make it so that each state indicates how you're allowed to move around
moving itself would not be a state
so the ShootState would say you can move at 50% speed
the StunnedState would say you can't move at all
a DashState would also say you can't move (because you can't decide to walk whilst the dash is happening)
solved it when with normal grappler mode but if i switch to normal mode when im swinging , it happens again 
nice ideas. Thanks for your advice. I'm going to try your approach now 
this is painful and im not sure how to fix it
This is a code channel, and that is not a code problem.
Delete it from here, go to #💻┃unity-talk and post an actual screenshot... not a photo to get help
it is a code problem tho
The msg I replied to has been deleted, I wasn't replying to you
oh sorry 😭
What I said was only half listened to as well, because they posted the same photo 🙄
why is this "really bro?"?
solution was easier than i think
well. it's still framerate dependent, so there's that
What happens if I have two timelines controlling one gameobject, one that enables it, and the other disables it at a certain time?
Sure, you came up with something that half works and will break in ways you won't immediately see 🤷♂️
the grappling hook is a bit weird.. like if i grapple forward then switch back and grappler backwards , the grappler doesnt make the player jump to the position i shot at. and also how do i make it so the speed of the player when jumping to the position after he shot the grappler not dependent on the maxDistance cause somehow , the player speed when jumping towards the grapple shot is dependent on how far you shot the grappler and that sucks , cause if you are close to a grapple able object , it barely moves you and im not sure how to fix it
also these are the func that are used in the player movement for the grappler
https://paste.ofcode.org/Mhc3LaRubQ6krGXKcNujqX the grappling script , hope its not too much! i jsut sent whats necesarry and whats needed!
Hi guys, can someone help me please? The animations won't play, and I got this error: 'Main Camera' AnimationEvent has no function name specified! My code: https://pastebin.com/GhDuQ0LT
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.
Also here's my camera nodes for animations:
Dont use animation component, you should use only Animator
sounds like one of the clip though is missing method / hasn't been linked in animation event
How can I do that then?
Open the offending animation clip , find the animation event and link it to method?
or just remove the event if you don't need it
guys where I can report a bug:)
!bug
🪲 To make bug reporting as quickly as possible, we made a bug reporting application for you. When running Unity choose Help->Report a Bug in the menu, or you can access it directly through the executable in the directory where Unity is installed. It will also launch automatically if you experience a crash.
📝 If your bug report is to do with Documentation, either an error, typo, or omission, you can report it by scrolling to the bottom of the page where you found the issue and click ‘Report a problem on this page’!
💡If your report is to do with a new feature idea, you can check the Unity Product Roadmaps page to see if your idea has already been planned.
For more complete instructions on how to report bugs, access: https://unity3d.com/unity/qa/bug-reporting
But that still doesn't play the animations
You asked about the Animation clip event
Do you get your debug logs
Yes
If your clips arent working, migrate them to Animator first
Then the animations are playing
Whether or not they stay playing is a different matter entirely
do you have any transitions out of those animations that are happening immediately?
No
Are you sure anim is on the object you think it is?
Yes
Show the animator states
show the animation inside the animator
Does anyone know how I can fix this?
Should look at them during playmode to see if it shows its playing.
what does the animation clips supposed todo?
Keep this window open and play the game. You should see a progress bar on these if it's in the state while that object is selected
Do you see the progress bar, and does it swap when you press or release shift
make sure you have the object with animator selected during playmode
so they're playing, they are just not doing what you think they are supposed to do
Yeah
So the animations are playing
Did you actually... animate anything with them?
Yeah
Show the inspector for one of those states
Okay, and does the CameraZoomOut animation clip actually animate anything
Yeah, I tested it, and it was playing very well, but it's not playing when I try to play it in the script
You can clamp the velocity after each grapple if that's what you want?
Like even if the grapple was done right next to you you can set min velocity to something higher that way it will always be "somewhat faster"
Good evening, how can I improve my game? Can anyone tell me my problem by looking at the screenshots? I optimized my code, but now the rendering part remains. I'd be very happy if someone could help. I'm new to optimization.
What should I do to fix it? I can't handle urp.
Oh, if you're using built-in I guess you can ask in #💻┃unity-talk
odd there's no channel for it
ok thank you
yeah i like the sound of that , but exactly do i do that?
Say for example you want min velocity of 25 right?
After your grapple speed calculation you multiply by the required amount if it's below 25
Say after calculation magnitude of your speed comes to 2, you multiply it by 12.5
If it's above 25 already then all is well and good and we don't adjust
thank you and also , do i do that in this func? since this is where the calculation of the velocity happens n stuff
sdk?
yes
yes?
Yeah , take a new variable for totalvelocity
Grab it's magnitude, if it's less than desired amount, multiply by adjustment and return the adjusted value
here
Android SDK Build-tools component is not found. Make sure all tools are installed in the SDK manager. Latest supported build-tools version is 30.0.3
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)
Random question time. In a lot of code samples (stackoverflow and the like) and video tutorials, I see people using var to declare a variable even though the variable type is ridiculously obvious (float/Vector3 etc). Is there any particular reason for this, or is it just lazy coding? lol.

Android SDK Build-tools component is not found. Make sure all tools are installed in the SDK manager. Latest supported build-tools version is 30.0.3
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&) i have it installed btw
huh?
Lazy coding mostly
so did you install the Android build tools ?
not really
oh
so basically remove this line and make a new vector 3 for total velocity and do all that other stuffs
just type out the issue
thats because you're typing needs work..
try making a full sentence before hitting enter..
how do I find out if the player's mouse is hovering over the green part of this image :(
depends what the green part is
Shift+Enter is a thing, Use it
What's the green part made of
im dum in unity
Yeah, tbh I figured it might be. only ask cause the one I'm looking at, at the moment declares position as var, direction as Vector3 and length as float. Was just weird to me that position was being declared with var instead of Vector3.
show that its installed inside the project settings
I don't know what velocityY and VelocityXZ is, and frankly could care less that's upto your desired way of calculating
What i meant about new variable totalvelocity was
Vector3 totalVelocity = velocityXZ + velocityY;
in the project settings. soo prefrences
I am displaying this image during the game as a "province" of a nation. The image is 1920x1080 but I only need the green part of the image to know when its being hovered on, not the entirety of the transparent areas
External Tools yea
What is it though
thats all i needed to hopefully understand for the solution , thank you alot
UI Image? SpriteRenderer?
wdym
Do you see the warning ?
image
yes
Np! 
so start by fixing that
idk how to tho
Then as long as you have the sprite set to tight instead of full rect and alpha as transparency normal UI interaction will work
Make sure you installed the tools from the Unity Hub instead.
guyz anyone used addressable bundle
where do you find that in all of these sprites?
Never had issues for android , make sure you set the correct paths.
This isn't directly code related, shouldprobably go in #📱┃mobile or #💻┃unity-talk
or you mean in here?
Actually don't even need to find "adjustment" I'm so dumb, sorry lol tired brain
If magnitude of TotalVelocity is < desired value
Just take TotalVelocity.Normalized * desired value;

dont i have to do totalVelocity.magnitude < my desired value?
Yea you do, but desired min value would be constant sooo
these appear 
Totalvelocity.magnitude in the if condition
Also 12.5f
youre missing an f on the 12.5
so i should just multiply it by 25?
Ye
Whatever you want your min value to be, totally upto you
Just keep it same in both places
thank you mr SexyYoungGod

also do i put f after the desired min value in the if statement as well?
or let it be without it
Doesn't matter as it's not a decimal number anyway
A literal with a decimal point is a double, by default
What should I do to solve the problem?
Hence the need for the f suffix to make it a float
f means float. In C#, decimal numbers are double by default, but Unity uses float for almost everything. The f tells the compiler "This is a float, not a double"
@wintry quarry ok I found what you are talking about. I attempted to do it with these settings, it said when I hover over the entire screen, that I am hovering over the image. Can anyone help?
Oh cool to know 
thats why they linked you to #archived-urp specific channel. I havent had to optimize that much urp just yet
can someone please help me with my problem :(
ok thanks
Show code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class tooltip : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
public int population;
public int stability;
public int economy;
public int economyTarget;
public Text txt;
public bool isHovering = false;
public void OnPointerEnter(PointerEventData eventData)
{
isHovering = true;
Debug.Log("Mouse entered!");
}
public void OnPointerExit(PointerEventData eventData)
{
isHovering = false;
Debug.Log("Mouse exited!");
}
}```
the whole idea is to enable a tooltip when you hover over the non-transparent part of the image but I will implement later
Change your logs to provide a bit more info:
Debug.Log($"Mouse entered {gameObject.name}");
See what object you are hovering over
i mean I only have the script on one object but ok sure
this happened when my mouse entered the border of the game screen, in a transparent spot
Transparent is irrelevant
Images are squares
but I want it only to register on a non transparent pixel
thats the whole problem
mightve found two problems , whenever i grapple forward then change my direction backward and grapple then , sometimes the player wont jump to the position but backwards , and the second problem at the end seems like the rope doesnt get destroyed after grappling , its not there visually but it still makes the player not go anywhere , only within the grapples maxDistance radius , im not sure how to fix it
https://paste.ofcode.org/bBKd3hu2WUCuMZaUrjs8FW , grappling hook script
Not really sure what causes it ngl
does anyone know how to fix these errors?
you should know, the messages are self explanatory
a little guidance?
what about the error message do you not understand?
it looks like the script is perfect
PlayerActions does not contain a definition for Dialogue
Or Attack
I don't care what you think the script looks like. What part of the error message do you not understand?
The compiler doesn't think it's perfect, after all (:
if that is true then your IDE is not configured, again
oh ok ill reconfigure the dialogue
no, you'll configure your code editor
!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
be right back
anyone know how to fix this? pls
!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, back to those error messages
what part of the error message do you not understand?
its typed in but doesn't accept that its a code
that's not something about the error message
I am asking exclusively about the error message
not about the code you wrote
oh in the console it shows that
but im not sure what happened to the files
I was playing the game and the script did not let me open the store unit
I need you to answer my question. What about the error message do you not understand? I don't need answers to unrelated questions.
If you completely understand what the error message is telling you, then say so
" "object" does not contain a definition for interact"
This means that the type named PlayerActions has no member named Dialogue
This doesn't match with the errors you're seeing here.
What are you currently seeing in the console?
No. It means that PlayerActions exists, but that it has nothing named Dialogue in it
A member is a field, property, method, etc.
anything you can put into a class, basically
Dialogue is in the script
the code of Dialogue
I think I may have to restore the game
I need to know what error is actually happening, yes.
is there an option, to restore each saved Unity project session, backup?
I'm guessing that you're using the input system's "Generate C# Class" feature. Is that correct?
Yes.
Did you modify the code it generated at all?
So, actions.Dialogue is of type object, which does not have a variable or function named interact
I was editing the input to mobile.
I don't know what that means.
Then I played the game, and the interact option did not open the dialogue.
you don't edit the generated C# code. you edit the Input Action Asset and let it regenerate the C# code.
I'm guessing they had another error, and used the Quick Action to add a new property into the class. The default type for this is object
So I checked the generation and regenerated a script .
That means you generated code that doesn't make any sense
tada
does no one know how to fix this? i really dont know how to fix it
my character controller script is interfering with a polygon collider i made for the camera, since the collider is setting the grounded state to true, so it thinks its on the ground and lets me jump continuously. I copied the character controller from a youtube tutorial, it says that i can change the groundcheck position to a certain layer but im not sure what i change
!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 all, so I'm currently losing the will to live. lol.
I'm having a brain issue regarding raycasting ScreenPointToRay.
It works if I 'manually' enter a value for my 'hitDist' float, but obviously it's not at all accurate. I need the distance to be the 'impact' distance between the minigun and the hitpoint, but need to get the hitpoint before I can do the calculation, so I'm a little confused as to how to go about it. 😕
Could anyone help please?
//MiniGun Mouse Targetting
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
float hitDist = 10f;
Vector3 targetPoint = ray.GetPoint(hitDist);
playerMiniGun.transform.LookAt(targetPoint);
Pic for visual reference.
You need to actually Raycast with that ray to find out where it hits
Yeah I thought so, that's the bit that confusing me as to how if honest.
I'm randomly getting errors complaining that I'm using a quaternion with a non-unit length. However, I'm not really buying it...
Here's what I'm logging:
Debug.Log(r + " " + $"{new Vector4(r.x, r.y, r.z, r.w).sqrMagnitude:N15}");
interestingly, I'm seeing the same values from sqrMagnitude as from magnitude...
i'm seeing a number of results with the same sqrMagnitude as the one that causes an error
I mean, 1 squared is 1
(the rotation is being passed to Rigidbody.MoveRotation)
maybe the original rotation is bad...?
Sorry to bug you man, but I'm still confused as how to use the screenpointtoray with the physics.raycast bangs head on desk
I'm going to guess it's a floating point precision error. Does Vector4 have a .normalized method?
You... use the ray
you have the ray
you use that in the raycast
Scroll down to the bottom. It shows you how to use a Ray.
↑
Oh pissing nora. sorry man, blind as a bat. lol.
Thank you.
Show the inspector for that code, with the m_whatIsGround variable open
How do I recognize in the code of this sprite when the player hovers their mouse over the collider of this sprite?
I upload my Folder on Google Play and i make a closed Test, i added my girlfriend to the TesterList but when She open the Link and come to Google play, Google say ("This app is not available") what is the problem? does it have something to do with the api level?
Because it works for me but it doesn't work for her
Perhaps that's what you want:
https://docs.unity3d.com/2019.1/Documentation/ScriptReference/EventSystems.IPointerEnterHandler.html
https://docs.unity3d.com/2019.1/Documentation/ScriptReference/EventSystems.IPointerExitHandler.html
Unless you want it to work with the collider then this one I suppose:
https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseOver.html
its set to an empty game object which is a child of the player sprite
I'm trying to make a coop fps game but I'm following a platformer video tutorial for it, i finished it once and i really liked the clean coding standarts etc.
Since the tutorial is using different systems, ( a static camera - mine has a playerCam, players only left,right,up,down - mine has fps movement) I'm kinda having hard time to convert the game into something else. Did anybody happen to try such thing before? Any suggestions would be helpful
damn still no help :(
Open what is ground. As I asked
how can i make a raycast ignore colliders that are triggers?
Use the queryTriggerInteraction parameter
https://docs.unity3d.com/ScriptReference/QueryTriggerInteraction.html
what useless information?
do you really not care about which layer you hit or how far your ray goes?
If anyone knows a fix , pls tell me , I really wanna fix this 
in this instance no
So keep them at infinity and everything
you can use named arguments here, I suppose
what do you mean
ah, that doesn't work here
Physics.Raycast(ray, out var hit, queryTriggerInteraction: QueryTriggerInteraction.Collide);
this screws up the method overloading
it thinks I'm trying to call a method that only takes three arguments
so, just pass Mathf.Infinity and the layer mask you're aiming for
you should probably have a layer mask here
what if i want every layer?
i need help with a error i have wail building it says error building player im new so i do not know
there must be another error
you'll get an error about the build failing
but that's not the actual problem
Hey! Having a little trouble getting a child box collider trigger to detect the player. The main script is on the parent gameObject
And the code:
private SpriteRenderer interactSprite;
// private BoxCollider interactionCollider;
private void Start()
{
interactSprite = GetComponentInChildren<SpriteRenderer>();
// interactionCollider = GetComponentInChildren<BoxCollider>();
}
void OnEnable()
{
WorldUIEventManager.onControllerSpriteChanged += UpdateUIElements;
}
void OnDisable()
{
WorldUIEventManager.onControllerSpriteChanged -= UpdateUIElements;
}
private void OnTriggerEnter(Collider other) // Notice it's now OnTriggerEnter, not OnTriggerEnter2D
{
// Check if the collider belongs to the player
if (other.CompareTag("Player"))
{
// Turn on the sprite renderer
interactSprite.enabled = true;
}
}
private void OnTriggerExit(Collider other) // Notice it's now OnTriggerExit, not OnTriggerExit2D
{
// Check if the collider belongs to the player
if (other.CompareTag("Player"))
{
// Turn off the sprite renderer
interactSprite.enabled = false;
}
}
private void UpdateUIElements(ControllerTypeSprites newSprites)
{
// Update your UI elements with the new sprites here
// Example:
interactSprite.sprite = newSprites.eastButton; // Assuming you have a SpriteRenderer or UI Image component
}
}
The Three Commandments of OnTriggerEnter:
- Thou Shalt have a 3D Collider on each object
- Thou Shalt tick
isTriggeron at least one of them - Thou Shalt have a 3D Rigidbody on at least one of them
Are any of the colliders or Rigidbodies 2D
Try logging other.gameObject.name before your if statement and see if you're ever colliding with something with the right tag
the thing is, I am not even getting into the OnTrigger code block
that is the starage thing
Show the inspector of this object and the thing that should be colliding with it
The collider I am trying to interact with is a child gameObject and the script sits on the parent
{
Transform playerTransform = PlayerController.instance.transform;
Vector3 direction = (_position.position - playerTransform.position).normalized;
direction.y = 0f;
Quaternion targetRotation = Quaternion.LookRotation(direction);
playerTransform.rotation = Quaternion.RotateTowards(playerTransform.rotation, targetRotation, _rotationSpeed * Time.deltaTime);
playerTransform.position += playerTransform.forward * _moveSpeed * Time.deltaTime;
if (Vector3.Distance(playerTransform.position, _position.position) < 0.1f)
{
PlayerController.instance.SetState(PlayerController.State.OpenChest);
_animator.SetBool("Shake", true);
_movingTowardsChest = false;
}
}``` im trying to make my player face the object this script is attached to. i cant seem to get the rotation correct
no. It just holds the scripts and interacts with InteractionCollider and ButtonSprite
The script needs to be on the object with the collider or the object with the rigidbody.
Rigidbodies contain child object colliders, but not all scripts
The Rigidbody is the one that calls the function, so what happens here is the player object with the rigidbody collides with InteractionCollider, and calls OnTriggerEnter on itself, any child objects with colliders, and on InteractionCollider.
Nothing tells it to call a function on the InteractionCollider's parent
Is there no way for me to referece the InteractionCollider in the parent script ? I already have reference to it .
but I do get what is happening here
You'll either need to put the collision detection on the other object and manually check the parent of the touched collider, or put this script on the object with the collider
{
Renderer selectionRenderer = null; // Declare selectionRenderer here
if (_selection != null)
{
selectionRenderer = _selection.GetComponent<Renderer>(); // Assign selectionRenderer here
if (selectionRenderer != null)
{
selectionRenderer.material.SetInt("_enableFresnel", 0); //disable fresnel when not in sight
Debug.Log("logging 0");
}
_selection = null;
}
RaycastHit hit;
if (Physics.Raycast(Camera.main.transform.position, Camera.main.transform.forward, out hit, 2, interactableLayermask))
{
var selection = hit.transform;
selectionRenderer = selection.GetComponent<Renderer>(); // Assign selectionRenderer here
if (selectionRenderer != null)
{
selectionRenderer.material.SetInt("_enableFresnel", 1); //enable fresnel when in sight
Debug.Log("logging 1");
}
_selection = selection;``` how do I make debug logging 0 and 1 only be called once inside to make it more efficient?
or should I let it keep being called
this highlights items, but not sure if I should let it keep calling 
I'm currently trying to finalise my puzzle game and am using raycasting and reflections on "mirror" objects. once the laser collides with the target it should open the door. i've been using iterative testing and it still isnt working does anyone have any ideas.
ah, maybe is like in my code?
but instead of enable fresnel and disable, make it open door xD i am not sure
and it has to not be camera maybe, it should be the laser thingy
can some1 plesae help me rn
line 47-57 is where it should open the door
it is entering the if statement as i can see with the debug log however isnt moving the door for some reason
if you only want it to call the log once, just get soem boolean values and set them to true after the first one is called then use them to not let it happen again e.g. an if statement
hmm, does it need getcomponent maybe?
so it can find the collider for the door
it should work by using the game object tag for the target as this works in other cases
unless raycasting uses different rules in these circumstances
raycasting needs collider I think
I tried it for the thingy, it wont interact without it, but maybe because I am using a different code 
but two videos i watched needed a collider for raycast
so maybe you need collider
Don't ask to ask, just ask . . .
yup
how do I make it stop calling, if ok, after bool I mean
im getting this error when i want to generate a c# class in the input system
yeah ive tried using colliders but they wont attach properly, i'll just have to speak to my teacher tommorrow
you need layermask for that, and getcomponent
i think
then assign a collider in the door, and assign that collider with the layer
just use an embedded if statement if(!isDebugged) {debug.log("Logging 1")} and do the same for logging 0
then make raycast find that layer, then set the door thingy to open
oh alright ill have a look tomorrow
please help quick i gotta fix it rn i have a presentation tomorrow
if I am doing a game which is based on a static battle system with bullets is it better to use logic or physics
im trying to use Cinemachine and im just trying to get the camera as a private gameObject instead of a public one, yet for some reason it doesnt work and ive tried
gameObject.Find
gameObject.FindWithTag
transform.find().gameObject
gameObject.transform.find
honestly im out of ideas
it worked perfectly fine when it was a public gameObject ;~;
private GameObject vCam;
void start(){
vCam = GameObject.Find("/Camera");
}
void OnTriggerEnter2D(Collider2D other){
if(other.CompareTag("Player") && !other.isTrigger){
vCam.SetActive(true);
}
}
void OnTriggerExit2D(Collider2D other) {
if(other.CompareTag("Player") && !other.isTrigger){
vCam.SetActive(false);
}
}
@cosmic dagger
Why can you not just drag it in
because its a prefab, and im planning on making it be generated while inside the program
Then assign the reference when you create it
please use simple words, my brain is currently hurting because ive been at it for the past 16 hours (not just this, but it has taken a significant portion of my time)
Create the camera.
Tell this script "Here is your camera" and give it that camera
so just a public variable or?
Public variable, property, or function, or whatever other way you feel like
cause again, im not going for that
is there really no other way? no way to make gameObject.find work, no way to GetComponent<>?
If it is even remotely possible to avoid using Find or GetComponent, you should
eh, at least this sorta works
public GameObject vCam;
void start(){
vCam.GetComponent<Cinemachine.CinemachineVirtualCamera>().Follow = transform.Find("Character");
}
no it wont.
Do not
Literally
just set the variable
i get this error when i want to generate c# class in the input system. please fix
when you make the camera
it does, it automatically sets the follow to the character
i cant do it in the room prefab
it doesnt allow for it
Absolute unity beginner here I'm trying to implement a working gun for an FPS (Pictured below). This project has barely started so far have the First Person camera working and can walk around the environment and such
So it seems like everything is in place except the part where the gun actually shoots. I was referencing a YouTube tutorial to help make this working (I can send if you think it's useful). I don't have the model for the bullet flash and impact which I was planning to get to later.
I can attach the full script below and also the fields that the script itself gives if that's of any use. I can see you're helping someone atm so there's no rush
Any help is appreciated thanks!!
using UnityEngine;
using TMPro;
public class GunSystem : MonoBehaviour
{
// Gun stats
public int damage;
public float timeBetweenShooting, spread, range, reloadTime, timeBetweenShots;
public int magazineSize, bulletsPerTap;
public bool allowButtonHold;
int bulletsLeft, bulletsShot;
bool shooting, readytoShoot, reloading;
public Camera fpscam;
public Transform attackPoint;
public RaycastHit rayHit;
public LayerMask whatIsEnemy;
//Graphics
public GameObject muzzleFlash, bulletHoleGraphic;
//public CamShake camShake;
public float camShakeMagnitude, camShakeDuration;
public TextMeshProUGUI text;
private void Awake()
{
bulletsLeft = magazineSize;
readytoShoot = true;
}
public void Update()
{
MyInput();
// Set Text
text.SetText("Ammo: " + bulletsLeft + " / " + magazineSize);
}
public void MyInput()
{
shooting = allowButtonHold ? Input.GetKey(KeyCode.Mouse0) : Input.GetKeyDown(KeyCode.Mouse0);
if (Input.GetKeyDown(KeyCode.R) && bulletsLeft < magazineSize && !reloading) Reload();
// Shoot
if(readytoShoot && shooting && !reloading && bulletsLeft > 0)
{
bulletsShot = bulletsPerTap;
Shoot();
}
}
private void Shoot()
{
readytoShoot = false;
// Spread
float x = Random.Range(-spread, spread);
float y = Random.Range(-spread, spread);
//Calculate Direction with spread
Vector3 direction = fpscam.transform.forward + new Vector3(x, y, 0);
// RayCast
if (Physics.Raycast(fpscam.transform.position, direction, out rayHit, range, whatIsEnemy))
{
Debug.Log(rayHit.collider.name);
// TODO: Look into fix for this
//if (rayHit.collider.CompareTag("Enemy"))
//{
// rayHit.collider.GetComponent<ShootingAi>().TakeDamage(damage);
//}
}
// Shake Camera -
// TODO: Develop CamShake class
//camShake.Shake(camShakeDuration, camShakeMagnitude);
// Graphics
Instantiate(bulletHoleGraphic, rayHit.point, Quaternion.Euler(0, 180, 0));
Instantiate(muzzleFlash, attackPoint.position, Quaternion.identity);
bulletsLeft--;
bulletsShot--;
Invoke("ResetShot", timeBetweenShooting);
if (bulletsShot > 0 && bulletsLeft > 0)
{
Invoke("Shoot", timeBetweenShots);
}
}
private void ResetShot()
{
readytoShoot = true;
}
private void Reload()
{
reloading = true;
Invoke("ReloadFinished", reloadTime);
}
private void ReloadFinished()
{
bulletsLeft = magazineSize;
reloading = false;
}
}```
So, you have a Room prefab that does not have a Camera component on it, and you want to assign a variable on Room to that Camera you have created. Is that right?
no, i have a room prefab that does have a camera component on it
is it ok for raycast to be called per frame? or no 
but it doesnt have a character component
So make the field public and drag in the camera
yeah i did that
So then what is the problem
Have whatever spawns the rooms have a reference to the player. When you spawn the room, set that room's camera follow to player
ill do that as soon as i get to the level editor in like 2 weeks, thanks for the heads up tho, appreciate it
And stop using GameObject as your object type when literally the first thing you do is GetComponent on it
Just make the variable the type you actually want
Everything is ok as long as it doesn't break your game or make further work a pain
Is this referring to mine
the command under raycast gets called every frame, worried it is not optimized
This little bit above the message means it is a "reply" to that message
my jump is also buggy as heck tho, i have a double jump and like, i can triple jump if i press the button at just the right time ;~;
everything else works as inteded so far though
I'm aware but the person was referencing raycasting which is a part of my script
Don't worry about optimization unless you either see a sudden drop in fps or you're near the mid/end of your project
sorry for confusion
It's all good
I have 84 UI elements that I want spaced evenly across a path, sort of like I have drawn.
- how can I define the path that I have sketched here?
- how can I evenly space my objects along it?
Bonus points if the transform of the objects can be perpendicular to the path
you could use the splines package https://docs.unity3d.com/Packages/com.unity.splines@2.5/manual/index.html
come on some1 please dm or something i need to fix this rn. i have a damn presentation tomorrow
Is anyone able to help here please
Yeah it just seemed a bit complicated to go from those splines to the canvas
you can get a position from any amount along your spline and put your elements at it
https://docs.unity3d.com/Packages/com.unity.splines@2.5/api/UnityEngine.Splines.SplineUtility.EvaluatePosition.html
do that for however many elements you have
bro some1 answer for the sake of god i need to fix this rn
ive already done that 10 times but ok
i get this error when i want to generate a c# class in the inut system
maybe try clarifying then so that people are more able to help you
did you google it? people on stackoverflow say it could be caused by an invalid character in your path
nah i couldn't find anything
show the inspector when you've got your input actions asset selected
what is an inspector
perhaps you should learn how to use unity
https://docs.unity3d.com/Manual/UsingTheInspector.html
now show the full error including the stack trace
you can click it in the console to view the entire thing
i have a double jump implemented in the game and sometimes i can get 3 jumps in if i time the button presses correctly
i dont even know how to go about bug fixing this tbh
this is what i have right now and ive been messing about with it trying to use context.started and something to do with Time, moving the jumpsRemaining-- about and nothing ever helped
public void Jump(InputAction.CallbackContext context)
{
if (jumpsRemaining > 0)
{
Debug.Log("Jumped");
if (context.performed) //if button is pressed = Big jump
{
player.velocity = new Vector2(player.velocity.x, jumpStrength);
animator.SetTrigger("jump");
jumpsRemaining--;
if (jumpsRemaining == 0 && maxJumps >= 2) ParticleFX.Play();
}
else if (context.canceled && player.velocity.y > 0f) //if button is let go = Small Jump
{
jumpsRemaining--;
player.velocity = new Vector2(player.velocity.x, player.velocity.y*0.66f);
animator.SetTrigger("jump");
if (jumpsRemaining == 0 && maxJumps >= 2) ParticleFX.Play();
}
Debug.Log("Jumps remaining: " + jumpsRemaining);
}
}
if i jump
and hold the jump button
and let go at a precise time and press it again
it does another jump that doesnt lower my jumpsRemaining count
and then i can jump again a third time
at which the particles will play
This is what it looks like when i do the 3 jumps
This is what it looks like normally
idk what happened but i reseted unity and the error is gone. like it still gives an error but its invisible in the console
then check the editor !logs
the debug isn't that helpful since you're not showing when you go into your blocks
im using unity's input system
its just whenever "W" is pressed
or when it's let go
right but, show that you're going into your statements more than how many times
I think they're referring to the if statements in the logs
what?
https://paste.myst.rs/ne3nzfy6
I used rb.velocity to make it move and make it graduatly stop with 98% decelaton rate.
However, it doesn't seem to move in the first place. What should I do?
a powerful website for storing and sharing text and code snippets. completely free and open source.
im sorry, im just a little confused as to what youre asking of me, my brain is mush right now
What exactly is the issue? Are you jumping more than the limit you've imposed, or does pressing a single key consume all jumps
i can jump more than twice, which is the issue
if i press jump at a precise time, one of the jumps doesnt get consumed
ok, then #💻┃code-beginner message
The logs could be firing if jumps remaining were greater than zero but neither jump cases were true, printing duplicates.
hold on, ill put the logs inside of the performed block
both blocks it seems
which one of unity logs should i send?
if (gameObject.GetComponentInParent<GameObject>().name == "Alqa City") //if Alqa City
Is that the right code to check for a child to get their parent's name?
i am not going to look through the log files for you. you can do that yourself. but you need to look through your Editor log like i said and check for relevant errors
public void Jump(InputAction.CallbackContext context)
{
if (jumpsRemaining > 0)
{
if (context.performed) //if button is pressed = Big jump
{
Debug.Log("Jumped big");
player.velocity = new Vector2(player.velocity.x, jumpStrength);
animator.SetTrigger("jump");
jumpsRemaining--;
if (jumpsRemaining == 0 && maxJumps >= 2) ParticleFX.Play();
Debug.Log("Jumps remaining in big: " + jumpsRemaining);
}
else if (context.canceled && player.velocity.y > 0f) //if button is let go = Small Jump
{
Debug.Log("Jumped smol");
jumpsRemaining--;
player.velocity = new Vector2(player.velocity.x, player.velocity.y*0.66f);
animator.SetTrigger("jump");
if (jumpsRemaining == 0 && maxJumps >= 2) ParticleFX.Play();
Debug.Log("Jumps remaining in smol: " + jumpsRemaining);
}
}
}
this better?
triple jump:
can someone please make sure my code is right, im not sure if thats a good way because I get errors
normal jump:
its the same?
wait no its not
it doesnt matter if i make the second jump big or small, it always makes it small for some reason
If you get errors it's probably not right
but if it goes big then i can just jump another time?
idk what this means :(
literally sobbing rn, my everything hurts and its just a stupid jump function ;~;
sounds like it's time to take a break then and come back with a clear mind
GameObject is not a component
GetComponent only gets components
i need this done in like 6 hours ;~;
so I need to get a transform in order to get the name of the object
your logic should be decrementing for each jump for how you have it, so all I can guess is you're appending values elsewhere.
and ive been trying to figure it out for the past 2 weeks
First off: Why do you need the name of an object. That should never be functionally relevant
so I can display it in a tooltip
only here:
private void GroundCheck()
{
if (Physics2D.OverlapBox(groundCheckPos.position, groundCheckSize, 0, groundLayer)) //if groundCheck box is overlapping ground = reset doubleJump
{
animator.SetBool("onGround",true);
jumpsRemaining = maxJumps;
}
else
{
animator.SetBool("onGround", false);
}
}
also if it is one specific province, it needs higher numbers than the rest of the provinces
but the character is not on the ground layer
That definitely sounds like something you should have in a script on the object, not having a different object checking its name
add a log there and try again
jumpsRemaining i assume?
ill do it in the else statement
what
when do you reset jumps
when the little gray rectangle is touching anything that is the ground layer
right, but look at your logs
and the player is the default layer
what about the logs?
OnGround is being called between your jumps
oh yeah
figure out why and you may come to a solution
thats really odd though
cause like
okay hold on ill get back to you
after inspecting the logs, this doesnt seem to be the case
yeah no, i dont know what was up with the logs then but it doesnt get called in the air
maybe it gets called twice in quick succession and somehow that messes something up?
what are people using for analytics? im looking to add them to my game to track some information, and i was wondering if there are any good/easy to use options out there?
yeah but, why doesnt it do it all the time?
wait nvm i just figured it out
or at least part of it
its because i never cancel the jump
so if i let it go after its fully done, it doesnt remove the jumps remaining
i think
ill test it again just to be sure
yep
thats the problem
Do consider what i've mentioned as it may still be a problem later. Usually what you do is just hold off on the casting until a frame or two before checking ground again.
ill keep it in mind for later
but right now i just wanna figure out what the deal is with the context.performed that is causing me the issue
isnt that also how you make coyote time?
and kinda similar way to make a jump buffer?
similar concept ye
ahh im getting side tracked
i just wanna figure this out and then go to bed
my brain is just fried but i cant quit till im done ;~;
okay
lets do this, so if the problem is with the button being held down until the player starts losing upwards velocity then that must be the issue right?
do i just add another clause to the if statement?
hold on, ill try something
yeah that did absolutely nothing, but i cant put in anything else
tried this btw if (context.performed && player.velocity.y <= 0f)
i mean, im just throwing crap at the wall, hoping something sticks :')
if i try adding player.velocity.y >= 0f then it only works if i jump while still going upwards
which is not the intended way for a double jump to work
i just realised how the callback function actually works, hold on imma go drink something rq and then be right back to try and figure out if i... well figured something out
im just sad now, nothing is working and i dont know what to do, ive tried modifying the if clause, ive tried adding and removing if statements, i feel like im at a dead end or that im tunnel visioned, but i cant see a way out nor can i turn my head to go back
don't reset your jump count if you're currently moving upwards
you should still let the player jump no matter what your velocity is
but if you're going up, even if your ground check succeeds, don't give the player their jumps back
i dont think this has anything to do with the ground checks, the logs didnt suggest that
for some reason i just dont think that the jumpsRemaining doesnt get deducted if i hold it for long enough
wait
context.canceled && player.velocity.y > 0f
if i dont cancel it until the player velocity is lower than 0 then the second part of the else if statement doesnt get triggered
i wonder if
adding an else jumpsRemaining-- doesnt work :|
but i still feel like it has something to do with the else if statement for some reason
O.O I THINK IT WORKS
I FIXED IT
IT WAS ONE STUPID ELSE IF STATEMENT OMG ;~;
i just wanna curl up into a ball and never emerge
but I did it
I FINALLY DID IT
@timber tide THANK YOU SO MUCH FOR OPENING MY EYES
public void Jump(InputAction.CallbackContext context)
{
if (jumpsRemaining > 0)
{
if (context.performed) //if button is pressed = Big jump
{
player.velocity = new Vector2(player.velocity.x, jumpStrength);
animator.SetTrigger("jump");
jumpsRemaining--;
if (jumpsRemaining == 0 && maxJumps >= 2) ParticleFX.Play();
}
else if (context.canceled && player.velocity.y > 0f) //if button is let go = Small Jump
{
player.velocity = new Vector2(player.velocity.x, player.velocity.y*0.66f);
animator.SetTrigger("jump");
jumpsRemaining--;
if (jumpsRemaining == 0 && maxJumps >= 2) ParticleFX.Play();
}
else if (context.canceled && player.velocity.y <= 0f)jumpsRemaining--; //THE DAMN LINE IVE BEEN NEEDING FOR THE LAST 3 OR SO WEEKS ;~;
}
}
it was just a stupid edge case i didnt know I needed ;~;
thank you to everyone that wasted their time, im proud to say it wasnt for nothing <3
Does anyone know how to fix this?
can someone refresh me how you do ors in a if statement
i always forget that one
are they just ||
so for example this would work
int randomnumber = Random.Range(0, 2);
if (randomnumber == 0 || randomnumber == 1)
{
BasicShoot();
}
to make it so if it is 0 or 1 it calls basic shoot
chicas
question
when i opened my project, it said that it needed to start on safe mode because there was a lot of compilation errors
i solved them all, but i need to know
i need to worry or something if the safe mode panel appears?
Correct. It is ||
No need to worry. Just open it and see what the errors are
Sometimes solving some errors lets the compiler get to a new point to "see" different errors
is there a way to easily have a if statement thats like if randomnumber = a number between 1 and 7
or do i have to just keep adding another or for each other number i want it to work for
If <= 1 or >= 7
I guess AND there
Not or
aight thanks
so like this right
if (randomnumber <= 0 && randomnumber >=5)
{
BasicShoot();
}
can anyone help me with this riddle? im trying to move my Inventory items to my chest. do I instantiate the same item prefab slot in the weaponchestUI tree as the Main Inventory and then send the ItemContent "ItemName&ItemIcon" (these are the details of the item prefab slot. Its a UI button with a text child, and a UI image gameobject) to the transform there and there is a maxslotlimit of one, so when you press the button in the Inventory it will play the method that will destroy the current slot in the inventory and Instantiate it in the weaponchest UI and then the itemContent would populate that slot. Or do I have to create another Item Prefab slot completely and call for the instantiation of that Item prefab and populate the itemName and itemIcon with the itemContent? any help would be nice
Yeah, looks good.
I would make variables for 1 and 5 though. But syntax-wise that should work
Few ways you can manage, one way in which you already instantiate all slots in your chest and inventory and simply move data around and refreshing the displayed image when changing a slot.
another way is move the slot game object entirely into the chest
Not a code question and don't cross-post
Yea i am trying this method since it is only one slot. https://gyazo.com/4b523b26580281f427fb643cc6a01896 (it looks like many slots but it is infact one Item prefab slot) The many slots is just an image. For some reason When I try this method to insatiate the Item Prefab into the chest UI through a button click, it just doesnt work
Kinda hard to say anything without seeing your setup and code.
Guys, I have a problem and that is that the reloading animation I have runs even when I no longer have ammo (it should only play when my clip is empty and the ammo is greater than 0 to apply it to the clip) ``` if (Input.GetMouseButtonDown(0) && !isCooldown && currentClipAmmo > 0)
{
gunAnimator.SetTrigger("Shoot");
StartCoroutine(Shoot());
}
if (currentClipAmmo <= 0 && !gunAnimator.GetBool("OutOfAmmo"))
{
gunAnimator.SetBool("OutOfAmmo", true);
}
if (currentClipAmmo > 0 && gunAnimator.GetBool("OutOfAmmo"))
{
gunAnimator.SetBool("OutOfAmmo", false);
}
if (currentClipAmmo <= 0 && currentAmmo > 0 && gunAnimator.GetBool("OutOfAmmo"))
{
gunAnimator.SetTrigger("Reload");
gunAnimator.SetBool("OutOfAmmo", false);
}
is the code right and is an animation thing?
or isnt right?
https://paste.ofcode.org/ZunTCDBfTdeHzaMsE8XPB5 Inventory Manager< https://paste.ofcode.org/3aMzunE9yE4T7rBUqPjnYB8 Item Controller<https://paste.ofcode.org/C5uXMm7dKy9nVnygbYPFVy <ItemWeapons https://paste.ofcode.org/DpFHGdNwPsVktHAEC3nEKe <Item Pickup script https://paste.ofcode.org/3aSBgZgHGYLxz4e36vHwHiv <InventoryItemController https://gyazo.com/1e30f0d4473cd45c784a34392e6f1a5e <Image of Canvas Hierarcy
Where's the part the runs on your button click?
I remove t hat scriipt
So what's the issue now?
https://paste.ofcode.org/5tZ9qqdf84ACh4sugixTfc <Button script
im having a hard time of getting this to work ^
Be more specific. What part exactly doesn't work.
The UpdateItemSlotContent metho and the TransferItemToWeaponChest dont work when I Assign this script to my Button and then in the properties of the button in the inspector I assign The OnClick properties to the script and call the instatiation method on click and it doesnt work
how do I use the particle system? do I make a singleton that controls all the particle effects or do I put it on every object that has particles?
"doesn't work" as in not being executed? Can you add debug logs and see if the methods are called when you press the button?
Up to you. If you need several particle systems running at the same time, you might need a pool in the case of singleton though.
in cinemachine, does it have change controls also when in that view?
Cinemachine has no controls
ah okok
how can we have different controls when something is toggled? (like if i press this switch, my controls would be based on cursor maybe or something else, might be an entirely different code)
would that be a dictionary inside character controller?
not sure how to start it
thank you steel, I will try 
errors related to editor code. have you written any editor code or use any assets that include any?
no, it happened right after i downloaded a picture to use as a background. but i reverted it and its still there
restart the editor
unrelated but my pc only makes noise when i press play in unity, ive turned my volume all the way down and it plays from inside the case, what tf XD
it had to do with the layout I had. I needed to just reset to the default layout and the error went away
{
string inputText = inputField.text;
Debug.Log("TMP_InputField text: " + inputText);
Debug.Log("PlayerNameSubmitted called with name argument: " + name);
if (!string.IsNullOrWhiteSpace(inputText))
{
playerInfo.playerName = inputText;
AddMessageToChat($"Ah, {playerInfo.name}, a name that will soon be known across the lands.");
inputPanel.SetActive(false);
}
else
{
Debug.LogError("No name was entered in the input field.");
}
}```
I can't get the input field to work properly. I can grab the inputfield.text but cannot pass it to anything. Here is the On End Edit (string) trigger
TMP_InputField text: sfsfsf
PlayerNameSubmitted called with name argument:
What am I doing wrong?
that blank box on the bottom right indicates you are sending in a blank string, you need to select the method name under the Dynamic options
There is a dynamic string section, and a static parameters section
The Dynamic String Option is greyed out, I read that somewhere but Couldn't figure it out.
oh my
Sorry
yea the option is under dynamic string, that Dynamic String is just a header
Thanks, appreciate you showing me that
Idk if where to put this question but. Im in my final year of school and for my project im making a vr escape room game and im trying to figure out how to code a number lock so you can rotate the lock and unlock it with a certain code. Is there any tutorial on this or advice? I have also made my own 3d model of the lock.
My advice would be to break the problem down. For instance, evaluating 3 digits/variables is pretty straight forward. Acquiring input would be what you'd make of it. Same with the visual effects - rotation and whatnot.
You should be able to map it to a signed angle / 360 degrees , map each section in degrees to specific numbers of code
so i should do mapping which is much easier
i thinks its more of like the part where
like when i grab a part of the lock and then it rotates
unless its very simple and its more complicated for me x_x
youre talking about a safe-style lock right?
ye so i have 2 lock designs
the safe one thats shaped like a dial
and ur normal one
yeah both should be easy to approach
wdym "visual code way" ?
like this
whatever you're most comfortable with using
Does Resources.Load<ScriptableObject>("foo") give me a new instance of the scriptable object, or does it give me the one assigned to other objects in the scene?
it's an asset, should be the same one.. I think
Hm. is there a way to check? I think it gives me a new one.
(oh, just printing instanceid(). checking now)
can't you just look for the specific kind of SO instead ?
What do you mean?
Yeah, I don't get why you need to load it, if you have references to it in the scene..?
Confirming it's the same.
I could assign it to a script, however, that is error prone. I might assign the wrong SO. I'm trying event channels, so I'll have tons of SOs as each SO is for one event.
I want to avoid linking things in the inspector, because I'm worried that when I change a variable, it'll refresh the inspector settings and thus delete all event assignments.
I don't really understand what the concern is about. If you're concerned messing something up in the inspector by accident, create one manager specifically for holding references to the SOs in a desired way.
I'm concerned that when I accidentally comment out an event und unity recompiles, it will erase all the listeners I set in the inspector.
what kind of events and what does that have to do with inspector and SOs
I'm using this approach: https://www.youtube.com/watch?v=7_dyDmF0Ktw
But instead of using the inspector to link GameEventListeners to methods, I want to explicitly write the link in Start.
Let's build the ultimate event system in Unity. With just 2 Scripts, you'll improve your programming skills and be able to organise and decouple your code much better! Less spaghetti code and more independent systems!
★ Join the Kingdom:
https://discord.gg/M2qfnUGxAz
★ Download the 2 epic scripts here: https://www.gamedev.lu/game-assets
★ Wat...
You would use version control to avoid such silly mistakes.
Agreed. But the shoulda, woulda, coulda is strong in this.
In other words: I don't commit to the git repo every 5min.
You don't need to. Only after major changes.
You can inspect and revert the changes before commiting
But you do you
I feel I have not understood normalized or raycast properly
//hit ray to touchposition vector2
Ray ray = Camera.main.ScreenPointToRay(touchPosition);
if (Physics.Raycast(ray, out RaycastHit raycastHit))
{
//Get "direction" of raycastHit to touchPosition from Player
Vector3 moveDir = raycastHit.point.normalized;
// Calculate movement distance per frame
float moveDistance = moveSpeed * Time.deltaTime;
//Move player
player.transform.position += moveDir * moveDistance;
Here, the player is moving. but not in direction of touch, as i expected. Where did I go wrong ? Thank you
you're normalizing the point that the ray hit which doesn't make sense, since that's a position and not a direction
Point is a position in world space. Normalizing it doesn't really make sense.
what you probably want to do is calculate the vector from the player's position to the point you want them to move to, normalize that, and then move them along it
You should get a direction to the point from your player and use that direction in your movement.
Damn, Prakkus is one step ahead🥲
Normalize means make the magnitude equal to 1, just to add to what they're saying
Which is why normalizing a position (which is the distance and direction from an origin point) does not make sense
i think this is a good strategy...maybe people will listen if we get enough people telling them the same thing 😄
yep, definitely go through this if you haven't: https://docs.unity3d.com/Manual/VectorCookbook.html
I'm new to coding and I making a VR game and I'm making a dial lock(safe style). I want to code it so the player is able to interact with the dial and rotate it to each number. However, I'm unsure on the coding on how to make it so when the player stops on a number it registers it as the first number and so on up to three digits until it unlocks the safe. I was wondering if there was any guide in general I can look at for VR.
Thank you @night mural @teal viper I will read documentation again.
Just check when the direction of the dial changes
Register the position when that happens
#🥽┃virtual-reality has some pinned resources for general vr
do unity object pools respect if the object trying to be requested is different than what is in the pool or will it just grab off the top. ie in the case where theres multiple different things stored in one pool. For example, if I have an enemy object pool with a bunch of types of enemies, will the pool request the correct enemy when grabbing it from the pool?
i'm not sure if you'll find a vr specific tutorial but i expect the logic owuld be the same either way
i think for me its more of the transferring like a 3d keyboard and mouse game to vr
Yeah, VR is a hard place to start though. I would try to implement it NOT in VR first so that you figure out what you're doing, then solve the VR problems. Otherwise you're trying to figure out too many things at once
What do you mean "correct" enemy?
- figure out how to make a working combination dial
- figure out how to interact with that dial in VR (it can still have the same internal logic!)
pretty sure the pools are by type, so if your enemies are all the same type you'll be ok, if not you need more pools
so rly its more of the code being the same and just adjusting it to VR
yep, VR changes how the inputs to your game are handled, but logic like 'how far was this dial turned' is probably just angle math, keeping track of rotation direction, counting how many correct angles they've hit and which one, and none of that has anything to do with VR
nvm i was confused how a pool worked, realized its very basic
Alright tysm ❤️
anyone know why?
when hes not injured his animations work fine however when injured it changes his animations, idle works fine it only happens when i injuredly move
anyone know why my textmeshpro is not showing in the world?
its like its there but not
Looks like it's behind that grass sprite or whatever it is
its not, even when its spawned in the skybox its not there
Can you rotate your scene camera around and look at it from the other side?
like this?
what's the mesh renderer part? i think this setup is wrong
you shouldn't need a mesh renderer and you should have your font selected in the TMP inspector, not as a material on a mesh renderer
I'd like to see the material setup as well
oh alright
it was working a second ago, not sure what happened
oh in that case maybe reopen your scene or unity real quick to make sure it's not a silly rendering bug?
Try disabling dynamic occlusion on the mesh renderer🤔
neither worked
if I place the prefab myself, it seems to work
only when its being instantiated
figured it out
was an issue when setting the color
alpha was 0 lol
Where?
LOL
with my object pooling
when i set the color the dictionary had alphas set to 0
lol
common mistake happened quite a few times to me 🤣
can someone share an example of how to use Application.persistentDataPath for WebGL? The docs say it's located at /idbfs/<md5 hash of data path>, but I can't find the exact url to check if the file is even stored. I also don't know how to read from the path
hello, i just have a quick question is it possible to change a game object midame so i have two gameobjects primary and secondary and iw ant people to be able to choose there weapons is there any way i can doo that in this script?
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using System;
public class WeaponManager : MonoBehaviour
{
public GameObject Primary;
public GameObject Secondary;
public int currentweapon;
public TPW tpw;
[Header("Guns")]
public GameObject pistol1;
public GameObject M4;
// Start is called before the first frame update
void Start()
{
currentweapon = 1;
EquipPrimary();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Alpha1) && currentweapon != 1)
{
EquipPrimary();
}
if (Input.GetKeyDown(KeyCode.Alpha2) && currentweapon != 2)
{
EquipSecondary();
}
if(Input.GetKeyDown(KeyCode.Q))
{
if(currentweapon == 1)
{
EquipSecondary();
} else if (currentweapon == 2)
{
EquipPrimary();
}
}
}
public void AssaultLadout ()
{
Primary = M4;
Secondary = pistol1;
EquipPrimary();
}
public void SniperLadout()
{
Primary = pistol1;
Secondary = M4;
EquipPrimary();
}
public void EquipPrimary()
{
Secondary.SetActive(false);
Primary.SetActive(true);
currentweapon = 1;
Primary.GetComponent<Gun>().Draw();
}
public void EquipSecondary()
{
Secondary.SetActive(true);
Primary.SetActive(false);
currentweapon = 2;
Secondary.GetComponent<Gun>().Draw();
}
}
I would like some elaboration on the answer to this post https://stackoverflow.com/questions/75419307/how-to-convert-base64-mpeg-to-audioclip-in-unity-part-2
In order to convert a base64 string into an audio clip, this is the code suggested by the answer
byte[] bytes = System.Convert.FromBase64String(data);
MemoryStream ms = new MemoryStream(bytes);
ms.Position = 0;
AudioClip GetAudioClip(bool threeD, bool stream, AudioType.MPEG);
However, I'm having trouble understanding the GetAudioClip method, as it doesn't seem to take any parameters related to the code above it
another answer suggested to use a memory stream, but does not elaborate any further. What I find really frustrating is that many answers assume I know certain things, when I don't
I feel like that answer isn't really correct. It doesn't make sense to me no matter how you look at it.
nonetheless, is the answer related to "memorystream" (looking into that rn) ?
I'm having that exact problem in the SO post, so I'm kind of desperate
That answer only works if the Stream is from the WWW class so as written is complete nonesense
where are you getting your clip data from?
base64
From a quick google, you should be able to create a clip with AudioClip.Create. but you need it in the right format.
no, that is the encoding format, where is it coming from
from the user I guess? The user records their voice on the web application
It then passes the base64 data to the webgl build
how are you loading it into your code
With the WebGL api https://docs.unity3d.com/Manual/webgl-interactingwithbrowserscripting.html
More specifcally SendMessage()
What web application? Is it a separate app?
The web application (react app) hosts/serves the webGL build
Well, then you'll need to figure out what format the data is in.
the data is base64 encoded mp3
