#๐ปโcode-beginner
1 messages ยท Page 160 of 1
What?
oh
Try reading this? ๐
i misread
my bad
i thought it said i cant do CoilyBoily =GetComponent
sorry
ok so the errors are gone,
but when i assign this it resets to none on play
GetComponent looks for the component On this script its calling from
if its not found it sets it to null
anything done in inspector gets overwritten by it
Showeth
this gameobject
so, this component, is not on the gameobject you just showed
wdym
I mean what I said, which bit don't you understand?
You have 2 game objects.
The component looking for CoillyBoily is on a different game object than CB .. so cannot find it.. which means โ๏ธ
right
If you're assigning something in the inspector, why do you think you need to do GetComponent<T>() ?
You don't, do you?
Do one or the other, not both
ok
thast good
but the script itself isnt working now
basically i have an object that moves to the player and i want it so when the player looks at said object, it stops
"isn't working"
that helps nothing
The object doesnโt stop
you have to provide the code
no
if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, Mathf.Infinity, layerMask))
A raycast is a tiny line, so you'd have to have it directly hit
Well I gtg for tonight so Iโll do it tmr
I believe CoilyBoily is the one with the movement ?
i don't see the ray doing much besides canMove on CoilyBoily
gotta check if the ray is hitting, as well as what's happening in CB
But he's gone now , so meh
yea true
if (otherFruit.fruitType != fruitType)
{
if (otherFruit.special_isSticky == true) return;
if (special_isSticky == true)
{
if (numOfSticks > 0) return;
stickFruitTogether(otherFruit);
return;
}
else return;
} ``` anyway to refactor this to make it look cleaner?
if (otherFruit.special_isSticky == true){}
else if (special_isSticky == true&&numOfSticks<=0){
stickFruitTogether(otherFruit);
}
return;
====================>
if (otherFruit.special_isSticky==false&&special_isSticky == true&&numOfSticks<=0){
stickFruitTogether(otherFruit);
}
return;
if (otherFruit.fruitType == fruitType) return;
if (otherFruit.special_isSticky) return;
if (special_isSticky && numOfSticks <= 0)
stickFruitTogether(otherFruit);
return;
Something like this? Not sure why you would need the last return, because you return out of everything.
that is better
Yeah sorry there is code below
void HandleFruitCombination(Collision2D collision)
{
if (justSpawned || hasBeenTouched) return;
FruitCombiner otherFruit = collision.gameObject.GetComponent<FruitCombiner>();
//fix this mess
if (otherFruit == null)
{
if(special_isSticky && collision.) numOfSticks= 0;
return;
}
if (otherFruit.fruitType != fruitType)
{
if (otherFruit.special_isSticky == true) return;
if (special_isSticky == true)
{
if (numOfSticks > 0) return;
stickFruitTogether(otherFruit);
return;
}
else return;
}
hasBeenTouched = true;
Vector2 midPoint = FindMidPoint(transform.position, otherFruit.gameObject.transform.position);
AddForceToSurroundingFruits(midPoint);
if (nextFruitPrefab == null) return;
if (hasSpawnedObject == true)
{
hasSpawnedObject = false;
otherFruit.hasSpawnedObject = false;
return;
}
Combine(midPoint, otherFruit);
}```
heres the whole method
most is irrelevant
Well then just add a curly brace with an indent on the first if.
if (otherFruit.fruitType != fruitType) {
if (otherFruit.special_isSticky) return;
if (special_isSticky && numOfSticks <= 0)
stickFruitTogether(otherFruit);
return;
}
Still seems cleaner then your version.
yup
Hey I am using an integer for my array called index but it does not let me set it to 0 and tells that int cant be converted into bool
show code
is your array bool[]
ok, then the way of accessing it
nvm I was being dumb, I fixed it
i have a list of lists of ints public List<List<int>> roomMatrix = new List<List<int>> { new List<int> {-1, -1, -1}, new List<int> {-1, -1, -1}, new List<int> {-1, -1, -1} }; and an array of gameobjects i need to make a loop that will check every index of the list of list of ints and if its 0 or above change that index in the list of list as in the array to something else so for example if the top left index was 0 or above the 0th term in the array would change then if the top middle was 0 or above the 1st element would change and so on but i dont know how i would compute this
just compare each increment?
wdym sorry?
read this, am lost, made coffee and read again, still lost
maybe draw something out cause I can't figureout the exact requirements here
but unless you need some sort of sorting, you're just doing some comparison on value changes between neighbors
I dont need sorting its the point of tho how can i do it without 9 if statements
In a multiplayer basketball type game would it make more sense to house the script that handles picking the ball up and throwing it within the player object or a game manager object??
It's a behavior of the player, no?
I'm trying to make a sword swing animation play when I press lmb can someone tell me what's wrong?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
in real life, the ball is picked up by player not by the judge or other audience....
so then should I use a reference to pick up the ball or a game event?
Hey is there any way to change the index of objects in an array
This question is incredibly vague
what is the problem
You use references for almost everything in some form or another
Presumably you'd use a Raycast or other physics interaction or query
When I press lmb nothing happens
Iin order to get a reference
you need a temp array/var
Start debugging your code
I did yet no issues found
Clearly issues were found
put debugs first make sure code is running, check console for errors
Explain what debugging steps you took and what you saw
K lemme tell u the errors I'm getting
I'm getting "๐ฆ๐ฆ๐ฆ"
What's happening is when I press lmb the attack trigger doesn't trigger
If you have List[y][x] then it would be y*3 + x
do you know if that part of the code is even running?
To return the assigned value to each space on this sort of grid you made
Did you put any debugs into the code to check if the code is even running and detecting your lmb?
this is real simple but I forgot how to do it if I have a number inside a vector like new Vector3(0, 0, 1.2) how can I make the 1.2 a double so it works
It's not detecting my lmb as I've stated
I thought it was double[1.2] or something like that
1.2f
nah thats a float
and if you do 1.2d it doesn't work
apparently not
it's saying I can't put 1.2 there because you can't put a float in a vector3
show where you put the debug.log
Vector3 expects a float
not a double
Vector3 accepts float not double
Prove it
nevermind I misread the error lmao
Under if (input.GetMouseButton(0))
if its not printing then the script is not running
I thought you could multiply vector3s whats the correct way to add value to a vector3 if you cant add or multiply them? I haven't done this in a while if its not obvious
You can add them
you can only multiply by float or add to another v3
You can also multiply them in 3 different ways
Yes but why
you can add vec3 with vec3 and multiply it with float
I swear my vs gotta be tripping cuz i tried to add and it didn't work
watch me try it again and it works and I look stupid lol
.Scale, .Dot, and .Cross are all ways to "multiply" vectors
vec3 * vec3 is not defined in mathematics
also make sure its the UnityEngine class one?
there is no such thing
assuming your saying the truth about ide @cursive viper
It is defined , just in many different ways
Namely these
bruh im tripping lmao I was trying to add vector3 to transform
I thought a transform was a vector3
cross product dot (inner) product is not multiplication to me, they have a different name at least
lol no transform a component that has 3 vector3s pos,scale, rot + other info ofc
It's a whole Component that contains lots of different information
Did you put a debug at the beginning of Update() to check if that's running?
Also check your CanAttack bool in the inspector since it's public and might be set to false so it never goes inside if (CanAttack) and thus it doesn't check your lmb
oh yeah check this ^
K gimme a min
oh nvm thats wrapped inside Input

thats why we said check if its running lol
I had that possibility in mind but I was like "no way that's the problem.."
U gotta know I'm stupid
unity says specifically line 16 is throwing a NullReferenceException https://hastebin.com/share/yijawefifa.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
then it must be the case
you are using the spriteRenderer before getting a reference to it
spriteRenderer is null
also use an array lol
yes, also this
thanks
imagine you having 15 sprites
new4Sprite, new5Sprite
also you can just make it a coroutine
IEnumerator Start()
{
spriteRenderer = GetComponent<SpriteRenderer>();
spriteRenderer.enabled = true;
spriteRenderer.sprite = newSprite;
yield return new WaitForSeconds(1);
spriteRenderer.sprite = new2Sprite;
yield return new WaitForSeconds(1);
spriteRenderer.sprite = new3Sprite;
yield return new WaitForSeconds(1);
spriteRenderer.enabled = false;
}
I don't understand anything at all because when I change the code from Raycast to SphereCast and it gives me errors but according to the page they say that it is the same, I mean it can be linked with another similar cast code
if (Physics.Raycast(Cam.transform.position, Cam.transform.TransformDirection(Vector3.forward), out hit, Range) && hit.transform.tag == "Enemy")
*you dont to new a waitforsecond, you can reuse the instance
yes just wanted to show on his case since i imagine he's a begginer
what's stopping us from using yaml to save the whole scene thingy?
the scene file is a yaml wdym?
save the game progress, using it
whats error say ?
is unity just not giving us the tool to to save the whole scene?
ctrl+s
file -> save
https://docs.unity3d.com/ScriptReference/Physics.SphereCast.html
find an overload that takes vec3 as its first two arguments
yea, if we can do that in runtime,it's an impressive save system already
because what states do you want saving at runtime?
Do you want your player position saved where it is? etc.. That could cause problems?
save scene in play mode?
when you open your editor it is in its run time...
yeah that Task.Delay doesn't do anything lol since you did not make the method async.
Also awake has async version but not Start
but like Xaxup suggested use a Coroutine as Start
awake can async?
indeed
argument 4 must be passed with the 'out' keyword
argument 3 should not be passed with the 'out' keyword
argument cannot be converted from unityengine.vector3 to float
I don't know what happens but if it is installed with raycast there are no errors, but I want to change to Spherecast and I don't understand why it gives errors if they are the same with raycast :- /
the direction is passed as third param
or make a ray with the 2 you have
var ray = new Ray(Cam.transform.position, Cam.transform.forward)
why does my gameobject detect collisions even though I never pressed "Is Trigger" anywhere?
OnTriggerEnter?
I thought you needed to press is trigger
yeah but if other object is trigger maybe it called too
Wdym by "detect collisions"?
In what specific sense?
using OnTriggerEnter
yeah your question isn't clear
Then yeah one of the two objects involved is a trigger
public class BallFondling : MonoBehaviour
{
public KeyCode grab = KeyCode.E;
public Transform ball;
public Transform cam;
private void FixedUpdate()
{
Vector3 fwd = cam.TransformDirection(Vector3.forward);
if (Physics.Raycast(cam.position, fwd, 5, 30) && Input.GetKeyDown(grab))
{
Debug.DrawRay(cam.position, fwd, Color.green, 10);
ball.position = new Vector3(transform.position.x, transform.position.y, transform.position.z + .5f);
}
}
}
anyone know why this code is not doing as intended? it is meant to place the ball in front of you when you look at it and grab it with "e". Tried asking chatgpt which didn't give any helpful info
I know there's probably a better way to do this too so if anyone has any input on that itd be appreciated as well
but I haven't checked is trigger anywhere
would it be better to store the boolean in update and then use it in fixedupdate if that makes sense?
yes
yes, you need to do that
ok bet lemme do that rq
how to select this collider?
collisions don't require "isTrigger" to be true..
A trigger lets you pass through the collider, and has OnTrigger
A collision stops you hitting the collider, but has OnCollision
If you're getting trigger enter, then one of the two colliders is a trigger.
Then why did you write OnTriggerEnter in your code?
Debug.Log the name of the object you're interacting with, and check the inspectors of both objects
BRUH I used on collision enter instead of on trigger enter
public KeyCode grab = KeyCode.E;
public Transform ball;
public Transform cam;
public bool grabPressed;
private void Update()
{
if (Input.GetKeyDown(grab))
{
grabPressed = true;
} else
{
grabPressed = false;
}
}
private void FixedUpdate()
{
Vector3 fwd = cam.TransformDirection(Vector3.forward);
if (Physics.Raycast(cam.position, fwd, 5, 30) && grabPressed)
{
Debug.DrawRay(cam.position, fwd, Color.green, 10);
ball.position = new Vector3(transform.position.x, transform.position.y, transform.position.z + .5f);
}
}
changed to this and still doesn't work
Delete this:
else
{
grabPressed = false;
}```
and put grabPressed = false; at the end of FixedUpdate
ohhh right because then it will turn it to false every frame even before the code inside the if in fixedupdate is executed right?
still doesn't work
ur layermask is prob wrong
I haven't managed it yet, it still gives me some errors :- /
I have ball at layer 30 and using layer 30 in the code
those layers aren't the same
that won't work, use a layermask
public LayerMask layerToHit;
Show errors
here
LayerMask mask = LayerMask.GetMask("Ball"); something like this?
except I replace mask to whatever I want it to be called?
I would do what nav wrote
just make the field mate
more info herehttps://unity.huh.how/bitmasks#bitmasks-and-layermasks
It's still giving me those errors
Have you shared your spherecast code?
just look at the signature of the code on docs
also use your IDE to make sure its the correct ones
if IDE doesn't show those param suggestions, configure it
yeah
I keep coming here with generic open questions. I'm coming from python where "There should be one-- and preferably only one --obvious way to do it." so I keep getting hung up on a multiple ways to implement things in csharp and I don't have much intuition what the "best" way is. I'm extending my sfx manager to be able to play spatial audio and optionally parent the audiosource to a moving object would you:
- Have one Play() method with optional parameters?
- Have 3 Play() overloads with different params?
- Have 3 different explicit Play, PlayAtPoint, PlayAtTransform?
here
thats your raycast code
That quite clearly says..... Raycast
ยฟDo I share the full code?
why you think you can simply replace "Raycast" to "SphereCast" (literally replace the text) without changing the parameters....
so 01 followed by 28 other zeros would be the layer I need?
and itd be better to do that then
public LayerMask layerToHit = LayerMask.GetMask("Ball");
just do it in the inspector..
I have changed some and it still shows me some errors
I don't know what I'm doing wrong : /
show what you changed
your ide is clearly not configured
use your code editor to your advantage and help your write it correct?
FindObjectOfType<GameManager>();
Can anyone explain me the logic behind this code please? Why do we put "()" Brackets at the end of the code? and can't we use the brackets instead of "<>"?
Because it's a function. You have to call the function
<> is to pass the Type into a generic function
this is c# syntax
What is the difference of it and GetComponent?
signature is public static T FindObjectOfType();
they're both generic functions but do same thing but differently
Nothing
They do different things but the syntax is the same
Both take a type and no function parameters
ok so I got it to work but now the ball starts absolutely tweaking
if (ballGrabbed)
{
ball.position = new Vector3(transform.position.x, transform.position.y, transform.position.z + 1.5f);
}
How do you get these overloads to show up like that? I've been using some crappy shortcut to expand them out
I am a bit lazy (I might not want to read the 2 pages you guys sent me) ๐ What is the difference?
probably hitting itself on the collider
the collider of the player?
this is Visual Studio Mac ๐
I checked that but the balls is quite far from the player
yeah I figured there was a better way than using the ball.position and transform.position
you're mixing physics with driect Transform position manipulation
also is that ball inside layerToHit
I'm also kind of lazy (I might not want to explain basic C# concepts and the difference between two functions already described in the docs) ๐ Go and learn, don't be lazy.
cause if it is it will keep spazzing out also
whats the physics part? if im just changing the position of the ball to the position of the player with a 1.5 added to the z
yeah it is, why does that make the ball tweak and how do I avoid it?
One of them gets components
๐ ๐
exclude ball from layerToHit
Show current code, show current error
but also if you're using rigidbody on ball you want to not use transform.position
the rest of the code wouldnt work anymore then though right?
if (Physics.Raycast(cam.position, fwd, 5, layerToHit) && grabPressed)
{
Debug.DrawRay(cam.position, fwd, Color.green, 10);
ballGrabbed = true;
grabPressed = false;
}
it needs to be in the layertohit
you want to ball to be hit or are you hitting something else?
If you do not understand the difference after reading the docs (and thinking about it for a bit), feel free to ask
I was going to read it anyways I asked it on purpose so I might learn a few extra things ๐
hold on let me post the entire script that will probably help
private void Start()
{
layerToHit = LayerMask.GetMask("Ball");
}
private void Update()
{
if (Input.GetKeyDown(grab))
{
grabPressed = true;
}
}
private void FixedUpdate()
{
Vector3 fwd = cam.TransformDirection(Vector3.forward);
if (ballGrabbed)
{
ball.position = new Vector3(transform.position.x, transform.position.y, transform.position.z + 1.5f);
}
if (Physics.Raycast(cam.position, fwd, 5, layerToHit) && grabPressed)
{
Debug.DrawRay(cam.position, fwd, Color.green, 10);
ballGrabbed = true;
grabPressed = false;
}
}
so you can put a bool or not do raycast once you have ball
float currentTime = timer.currentTime;
int minutes = Mathf.FloorToInt(currentTime / 60);
int seconds = Mathf.FloorToInt(currentTime % 60);
int milliseconds = Mathf.FloorToInt((currentTime - Mathf.Floor(currentTime)) * 1000);
timeLeft.text = string.Format("{0:00}:{1:00}:{2:000}", minutes, seconds, milliseconds);
Anyone could help why are te miliseconds always displaying 000?
would be easier if you explain a bit the goal of your game / mechanic
maybe it's too fast you can't see it moving ๐
I don't need to see it moving wdym
I am joking
It seems reasonable to me. Get the decimal part, multiply by 1000, floor that.
yea i tried many approach
tangent: you might find TimeSpan to be useful here
it lets you specify a timespan and then format it to a string
so could I do something like
private void Update()
{
if (!ballGrabbed)
{
layerToHit = layerMask.GetMask("Ball")
} else {
layerToHit = layerMask.GetMask("some random unused layer")
}
}
???
is timer.currentTime actually including a decimal portion
same result, always returns 000
Try using the debugger to inspect the values, so you aren't possibly running into issues with the string formatter
to be able to grab the ball, and then once its grabbed press another button to launch it
it is a float so i guess
or is it just giving you whole seconds
Why
it is a float
so you dont need raycast after ball is grabbed, make a bool.
or store ball in variable
Floats can also store whole numbers
Actually check instead of just assuming
yeah like the other code I posted? where the layermask thing is in Update instead of Start?
you could do this by logging currentTime, or by inspecting with a debugger
that might be the case, the timer is set to "900" in the inspector (15 minutes)
then im doing currentTime--; in a coroutine
every second
So, the milliseconds are 0 because the milliseconds are 0
right
You literally aren't tracking them
makes sense ๐
can't do it in a coroutine then
alteast not with wait for seconds (1)
you have the bool already then just parent the ball to player no? why are you manually setting its position
If you want this to be updated every frame, why not just... update it every frame
subtract deltaTime in update
that'll actually be more accurate
since subtracting 1 every time WaitForSeconds finishes will cause some wobble
it was easier for me to make it into a coroutine, because im also playing a sound effect and updating a text
private IEnumerator Countdown()
{
yield return new WaitUntil(() => stopTimer == false);
while (currentTime > 0)
{
yield return new WaitForSeconds(1f);
currentTime--;
if(currentTime <= 5)
{
lastSecondsPlayer.PlaySound();
}
UpdateTimerText();
}
onTimerEnd?.Invoke();
}
it will actually take 1.03 or 1.01 or 1.02 or whatever seconds for that to finish
would I then unparent it after I launch it or something?
can you parent objects to other objects inside of a script?
pretty much
Do that in update when the seconds value changes
so I do another bool that checks if the ball is parented, inside the if method that changes the position, I nest another if method that only moves the position of the ball once if its not parented yet, then after moving the ball it parents it to the player?
lemme try that rq
private void Update()
{
if (stopTimer == false)
{
currentTime -= Time.deltaTime;
if (Mathf.Floor(currentTime) <= 5 && !isSecondElapsed)
{
lastSecondsPlayer.PlaySound();
isSecondElapsed = true;
}
if (Mathf.Floor(currentTime) < currentTime)
{
isSecondElapsed = false;
}
if (Mathf.Floor(currentTime) != Mathf.Floor(currentTime + Time.deltaTime))
{
UpdateTimerText();
}
if (Mathf.Floor(currentTime) <= 0)
{
onTimerEnd?.Invoke();
stopTimer = true;
}
}
}
that will work i guess
you're overcomplicating it
UpdateTimerText should run every frame.
or else it's not going to show milliseconds very effectively..
that function is not for updating miliesconds
i show miliseconds only in the summary screen
the UpdateTimerText() is only minuted and seconds
no miliseconds in there
private void UpdateTimerText()
{
int minutes = Mathf.FloorToInt(currentTime / 60);
int seconds = Mathf.FloorToInt(currentTime % 60);
timerText.text = string.Format("{0:00}:{1:00}", minutes, seconds);
}
Vector3 fwd = cam.TransformDirection(Vector3.forward);
if (ballGrabbed ) return;
if (Physics.Raycast(cam.position, fwd, 5, layerToHit) && grabPressed)
{
ball.SetParent(cam); // etc.. make your own point to parent to infroot of cam
Debug.DrawRay(cam.position, fwd, Color.green, 10);
ballGrabbed = true;
grabPressed = false;
}```
You just need the method to launch the ball / unparent it and set bool `ballGrabbed` false
int oldSeconds = currentTime.FloorToInt();
currentTime -= Time.deltaTime;
int newSeconds = currentTime.FloorToInt();
UpdateTimerText();
if (oldSeconds != newSeconds) {
//You've changed seconds, do whatever you want here
}
I am trying to make it so, when the place is not touching "ground" it runs the function "EndGame" but it says that "OnCollisionEnter" it's not working
How can I make it work?
You have a function in your function
ohhhhhhhhhhhh ok makes a lot of sense. can you do ball.parent tho? as ball is just a transform not a gameObject
the function set parent is on the Transform class
no problem ๐
would probably be on this for hours otherwise lol
the worst part is when u figure something out sometimes and realize if you had come up with a certain way to do it 4 hours ago it wouldve been done already
exactly, mine was figuring out I just needed a dictionary in the end ๐ฅน
one time I tried to implement gun spread by having 4 gameobject children of the player rotate at certain degrees depending on the gun type and then casting a ray in the forward direction of each of those game objects and calculating the "diamond" shape that the raycasts made when they hit a collider and firing another ray inside of that "diamond" ๐ญ
then some guy on the unity discord turned my paragraph of code into two lines without the unecessary gameobjects
why is the audio clip not playing?
by the way the code still doesn't work lol, now the ball tweaks slightly less for like 5 seconds before it just noclips through the floor lmao
Use Debug.Log to see which code is running and when and if that matches your expectations
can show what you mean "tweaks"
yeah hold on
do any video recording software come with windows?
yeah but obs is better imo
windows key + G iirc
it worked when i used a box collider instead of a capsule
also I think if you want collisions while holding the ball then parenting is not the solution and might need to use rigidbody instead
here it is
I, have, a, question ๐๐ ๐
then ask?
I have put it in a FixedUpdate function on purpose
Is it going to update or just gonna run once?
why
it's not going to run at all
you made a local function
Functions don't belong inside other functions unless you're an advanced programmer who knows what you're doing.
and you are not calling it
ok and can u send ur current code from link https://hatebin.com paste it and save send link
I didn't know you could even put functions inside functions without an error
its only 40 lines should I still use hastebin?
no I mean if I code it as a function on it's own
it's valid syntax
called local functions
is it gonna only run once?
that is what you have to do , yes
If you put it on its own then your question is irrelevant
its gonna run whenever the conditions are met for it to trigger
it's going to run whenever a collision happens
that's the point of OnCollisionEnter
yea much easier to read
ohhhh
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
๐ Thanks
that was much easier than I thought lol I uploaded it before you even answered if I should use it or not
can you screenshot the inspector for the ball btw
btw even though this code includes the line
ball.position = new Vector3(transform.position.x, transform.position.y, transform.position.z + 1.5f);
on line 34 I tried running it without it and didnt work
this is for the parent
also your scale is inverse, always keep root object at 1,1,1 with all the components and meshes resized as children
can I make it not kinematic or whatever its called while its not on the floor or being launched and then it wonr move?
yeah kinematic is what you want sure to not make it move
but you still need to manually move it iirc
how do I do this
I also have done it in the past where you can keep the ball dynamic rigidbody if you dont want it to clip through walls
How can I code my player, so, if it's not touching ground. It prints "GameOver"
That was what I was trying to code
if(!isGrounded)
Debug.Log("GameOver");
many ways to check for isGrounded
many tutorials on that
this is a dynamic rb ball
private void FixedUpdate()
{
if (currentObj)
{
Vector3 dirToT = pickupTarget.position - currentObj.position;
float distToT = dirToT.magnitude;
currentObj.velocity = amount * distToT * dirToT;
}
}```
just take the function out of the fixed update and make it its own thing, then debug what is going on
you were told this the other day when you did the function in a function as well
I will have a look at it
I fixed that my friend, please read my question carefully. I am sorry if I made you angry
the ball still bugging
if (Physics.Raycast(cam.position, fwd, 5, layerToHit) && grabPressed)
{
Debug.DrawRay(cam.position, fwd, Color.green, 10);
ballRb.isKinematic = true;
ball.position = new Vector3(transform.position.x, transform.position.y, transform.position.z + 1.5f);
ball.SetParent(cam);
ballGrabbed = true;
grabPressed = false;
}
ballRb.isKinematic = true;
ballRb.MovePosition(new Vector3(transform.position.x, transform.position.y, transform.position.z + 1.5f));
im back
public CoilyBoily CoilyBoily;
public float speed = 20f;
float xRotation = 0f;
public LayerMask layerMask;
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
CoilyBoily = GetComponent<CoilyBoily>();
}
void Update()
{
float xAxis = Input.GetAxis("Mouse X") * speed * Time.deltaTime;
float yAxis = Input.GetAxis("Mouse Y") * speed/2f * Time.deltaTime;
xRotation -= yAxis;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
Mathf.Clamp(yAxis, -90, 90);
player.Rotate(0f, xAxis, 0f);
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
}
void FixedUpdate()
{
RaycastHit hit;
if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, Mathf.Infinity, layerMask))
{
CoilyBoily.canMove = false;
}
else
{
CoilyBoily.canMove = true;
}
}
}
ah ok that seems like a better way to move the ball
please use links for large code
let me know how it works its been a while since I used kinematic
i will remember that for future reference
@rich adder all this code will still work in multiplayer as long as instead of using references I get the rb and transforms within the script and then just sync the position of the ball and players and such right?
you still showed the wrong script
no
assuming I successfully somehow manage to implement multiplayer in a game ever
this is the other one
Mission complete o7 (I did it with OnCollisionExit)
honestly I would not worry about multiplayer this early, you should learn a little more
thanks for the help Xaxup
multiplayer needs to be build from scratch its harder to implement into a made game
which do you want
My answer was kinda meme but I'm glad it helped you lol
You are evil
The code is sometimes in the question you write
Read your question again I didn't make anything particular to write this pseudo code
yeah but then theres no point in even making this project since the idea is multiplayer oriented, plus im just messing around not like I have to turn this into anybody. If I make something cool good and if not back to the drawing board.
but yes I know I have to make multiplayer from scratch im just messing around with this rn to get an idea going
no
well def learn more before doing multiplayer parts
learning while doing multiplayer wont be fun i promise lol
can you do the bot command for teh links
!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.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
yeah might put this down for a bit later while i experiment with other stuff
but for now the ball has reached unprescedented levels of tweaking
if (Physics.Raycast(cam.position, fwd, 5, layerToHit) && grabPressed)
{
Debug.DrawRay(cam.position, fwd, Color.green, 10);
ballRb.isKinematic = true;
ballRb.MovePosition(new Vector3(transform.position.x, transform.position.y, transform.position.z + 1.5f));
ball.SetParent(cam);
ballGrabbed = true;
grabPressed = false;
}
here you go
first make sure the pivots are correct , i see you're in center mode
OHHHH I figured out the issue
I think
so did you look at the CanMove bool and make sure its set properly, look in the inspector ?
the main camera is a child of another object called camholder
makes sure its..?
and the player gameobject has several children
oh
lemme see\
I think the best course of action would be to give the player another child called "ballHolder" and parent the ball to it
or do you think thats overthinking it
yeah also scale plays important part as well as pivots
both should be 1,1,1
im fairly certain its fine
well i want proof then
How are you "fairly certain". Did you check or not
i did
in playmode?
in both
and what is the result the screenshot above?
so CanMove is false in playmode?
When I specifically write position.y < -1 does the job. Are there any reasons it doesn't work this way?
so you just lied
What on earth is the code in the screenshot suppsoed to be doing?
position is a property
it is not a function
only functions can be invoked with (parameters)
if the players position is -1 it print "you are dead"
in the y axis
Because position is not a function
ok well I just explained why the syntax you used doesn't work
because it makes no sense
hmm ok
if (player.transform = new Vector3(0, -1, 0))
it worked when I did position.y < -1
yes because that makes sense
That doesn't work for many reasons
you are checking if the value of the property is less than -1
i didnt say it did
Yes, because position.y is a number, and you're checking if it's less than -1
oh wait that is overthinking it?
I thought you meant yeah thats a good idea and I did it lol
its not working either way the ball doesn't do anything now
Why write it if it's not supposed to work..?
lmao
if (Physics.Raycast(cam.position, fwd, 5, layerToHit) && grabPressed)
{
Debug.DrawRay(cam.position, fwd, Color.green, 10);
ballRb.isKinematic = true;
ball = ballHolder;
ball.SetParent(ballHolder);
ballGrabbed = true;
grabPressed = false;
}
thanks for the help guyz
you said you screenshot it during playmode
You should seriously consider learning basic C# syntax instead of coming here with some buck-wild hypothetical guess at the syntax every ten minutes
There are many useful links in the pins
i said i looked in playmode
๐
so what good is that screenshot if it wasn't in playmode ๐ค
anyway put debug.log inside your methods there and see if the bool is triggered at all through function
You've got like three more digicredits before I start charging per answer
HAHA
Do you mind checkings dms?
Do you mind paying my consulting rate
how much is it?
pretty fair
Paid in advance
Thatsโฆcheap
Ill charge a quarter of that, but ill get the answers wrong half the time and ill be using google to answer most of them
I'm competitively priced until I get professional references
Yoโve got mine
I sometimes try to google them aswell ๐ That's why I end up here (sometimes I don't)
It's fun learning how to code, but it's more fun trying to code with some theory and 0 knowledge (because I get digiholic busier ๐ )
And the most fun is solving the problems yourself
Bro, that's called "torture"
nah +1 to Uri
No one becomes a programmer without on some level enjoying the pain
LASOD;JKHG[OIJFASDG
lmao
I know it's sometimes kinda annoying that I keep on asking questions, but honestly I do (sometimes) try to solve my problem on my own.
and why do we endure the pain? ofcourse to have more advanced pain on more convoluted problems!
pain grinder 2000
Daddy GPT decided to take on the pain for the boys
can i change the max polyogns limit
What max polyogns limit
No, I believe they specifically said polyogns
I never hit it so I have no idea what it is lol
for a convex mesh
its aight i just use a capsule collider
Yeah I'm not sure what a polyogn is either but they seem to be very confident in what they say so we should probably listen to them
we both know i meant polygons
You probably should be using primitves in the first place
mesh colliders are expensive
if you hit limit on convex you prob have something guaranteed to implode and to complex
I'm the one that made the spelling comments, be snarky in my direction
I'm having issues making an object transparent. Every time I use the fade render mode my body no longer overlaps the visor. I can't find anything on google about it. I just want my player to become transparent but so far the only way I've found to do that is with the fade/transparent rendering mode on my material.
Transparent shaders do not do depth well. Also this doesn't really have anything to do with code
well i figured there might be some stuff at runtime to mess with it but yeah ill keep looking thanks
anyone willing to review this yanderedev type script and explain to me why is my velocity clamped at 30 while sliding in air?
you have a max velocity method there so why don't you debug that
if you're not supposed to be calling it while sliding then throw out some more logging
or better yet, use breakpoints
ill try thanks
{
horizontalInput = Input.GetAxis("Horizontal");
forwardInput = Input.GetAxis("Vertical");
transform.Translate(Vector3.forward * Time.deltaTime * speed * forwardInput);
transform.Rotate(Vector3.up, Time.deltaTime * turnSpeed * horizontalInput);
}```
how can i adapt this to limit the rotation of the object (a car)
basically when i press a or d the object will rotate in place and it feels unrealistic so im trying to fix it but i have no idea how
use a car controller
with wheel collider
oh okay thanks
hi I have a little problem I know I had already asked several times but they helped me I installed something and now my script looks like this and I don't know why it displays this : Can't add script component 'PlayerController' because the script class cannot be found. Make sure that there are no compile errors and that the file name and class name match. ```c#
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.EventSystems;
public class playerController : MonoBehaviour
{
public float movespeed;
private bool isMoving;
private Vector2 input;
private void Uptade()
{
if (!isMoving)
{
input.x = Input.GetAxisRaw("Horizontal");
input.y = Input.GetAxisRaw("vertical");
if (input != Vector2.zero)
{
var targetPos = transform.position;
targetPos.x += input.x;
targetPos.y += input.y;
StartCoroutine(Move(targetPos));
}
}
}
}
IEnumerator Move(Vector3 targetPos)
{
isMoving = true;
while (targetPos - trasnform.position).sqrMagnitude > Mathf.Epsilon)
{
Transform.position = Vector3.MoveTowards(transform.position, targetPos, moveSpeed * Time.deltaTime);
}
Transform.position = targetPos;
isMoving = false;
}
you have very obvious compiler errors. Please learn some C# basics
okay how
you also have non compiler errors which will mean even if you fix the errors it wont work
!learn
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
and how to make it work even if you know how to do C#
Learn will teach you that as well
but I can't learn I don't have time if only
it is for school
I have to do a project presented and I chose to create a little game
Hi! I need some help. I want to make a 2-player card game for a school project.
I'm using Lobbies to connect the 2 players and I have an issue: I'm testing it with ParrelSync, but I get this error:
Unity.Services.Lobbies.LobbyServiceException: player is already a member of the lobby
because the players have the same ID. Is there any way I can make the players generate different IDs?
why would you do that with absolutely no knowledge or experience?
we have to choose a project that is close to our hearts, I thought it would be less complicated, the problem is that I understand almost nothing
I understand what I write in scripts but when there is an error having to resolve it without help is quite hard
Hello, could you provide your code so that I can look into it
You can't just ask for help here with no knowledge of how Unity works, at least start learning by yourself by watching youtube tutorials for beginners, there are plenty of great quality
I completely agree with you but when you speak French itโs not so simple
that's true, but to be a developper you kinda have to learn english
I found a tutorial about Lobbies on YouTube and the guy had no problem with this code. Someone in the comments said they had the same problem as me and the guy didn't explain why he didn't have said problem in the video (He just hit Build and Run). He pointed that person to his Discord server because someone encountered the same issue. There are other scripts that link the Join and Host buttons but they mainly use functions from here.
Do you have to use unity? You can make a very easy game just using like python, or even just in javascript. Something like snake, or a recreation of any game.
If this isnt a unity specific class, save yourself the headache because the people marking it wont care if it's a shitty game in unity vs a shitty game in python. Except one is much easier to make
i just want to make a game similar to Pokรฉmon Platinum and have a character move in a 2D world and capture beasts, it seems hard to me now
Can you specify what namespaces you're using
tristan try using RPG Maker
okay do you have a link good for official page ?
You have to pay for RPG Maker
oh shit
Unless you, you know.
Should my weapon be under the player game object or camera holder
Can someone just tell me how I can correct my mistakes and tell me what should I do to make it work in less than 1 hour because I have to finish it by July
Do you have your IDE configured, are your errors underlined in red
There's a bunch of bloat. Some of these auto initialized when I wrote certain function
idk how to make a good cooldown systemm.. this one isnt working
Get rid of bloat
yes it was but after saving and closing and reopening it is no longer displayed in red
You can delete the ones that are greyed out
Guys, help please
So, look at the lines that are underlined in red, and see what the IDE says the error is. Then you can look up how to fix it and what your syntax should look like
how can I make a collider phase through another?
That's a big "just". Like me, I "just" want to make a billion dollars
me too
Does it specifically have to be a collider? There is an "is Trigger" property in the component which just phases through all colliders
me not dollar me euros
any1
Did you install some extensions for your IDE to use these namespaces ? My VS Code doesn't recognize Unity.Servies
Services
how can I make an object render on top of everything else and make it a trigger inside of a script
I would like to but the errors are no longer displayed and I don't understand why in the guy's video it works and I don't
You can make it a trigger from the collider inspector. As for rendering on top of everything else you can camera stack
it's up to you. there is no direct way to do it. this is my way to go
I used to do the same but there aren't any differences how you arrange the hierarchy, right?
well to do what I need to do I cant do it from the collider inspector because then the player would need to have access to the inspector lol
If you're talking about activating a trigger, you can refer to this https://docs.unity3d.com/ScriptReference/Collider.OnTriggerEnter.html
I think probably making it a trigger isnt the way to go here anyway
I just want it to phase through another specifc collider not every collider
ofc it matters, you can do other way but this is just the simplest imo
Again, all colliders have this box to tick. The collider will phase through everything. You can use OnTriggerEnter to check if colliders itneracted with your trigger
I meant in means of Quality-Of-Life and probably performance, not functionality
The guy from the tutorial manually wrote them and so did. They work. The main problem is that I have the same Player ID on both instances and that's what causes the error. I mainly want to know if there is a way to force ParrelSync to generate a separate ID or if there is an alternative because I don't want to load all of the code on my laptop and test it with a VPN.
thats really not what I need I just need the object to phase through a specific other collider
not every collider
and I dont need it to be a trigger either
What's the use case? Maybe you can just use the physics layer matrix here
Tell us specifically what you're trying to achieve. This is vague
thanks
trying to achieve phasing a collider through another one lol, other guy already posted the link
performance wise doesnt matter. QoL = just make a global refference to your WeaponHolder and you can easly spawn, destroy prefabs into it for weapon switching
Didn't catch the Host's Player ID in the 2nd screen shot (It's the same as the client)
You can ignore collisions
Oh shit he alr posted it nvm
have a ball that the player can hold, however when the player holds it and looks down the ball collides with the floor and the player causing the player to begin flying. I was thinking of having the ball render on top of the floor and having it ignore the floor, that way the player can look down without flying
i mean if you use GameObject.Find then performance wise it matter (very slightly) because unity will search for the gameobject from top to bottom each time in the hierarchy. thats why its a good solution to cache it in a singleton refference
Yeah, the docs should help. As for rendering on top of everything else, there are many simple tutorials in like under 2 minutes
Camera stacking is a common method
Sounds more like it shouldnt collide with the player, though it depends what "holding" is in this.
if it doesnt collide with the floor it would never reach the player, and it looks kind of weird when it starts hitting the floor and getting closer to the camera so I figure itd be better to make it not collide with the floor than the player so it looks better
ill show a video tho
im stupid lol
definitely should not be colliding with the player
maybe the floor and the player for best results
maybe should avoid all collisions while holding then stop ignoring them once launched
how can I unattach an object from its parent?
set its parent to null
in the new render pipelines i think they're trying to go away from that
just using seperate Renderers in the piepeline
still a legitimate approach in teh Standard Renderer Pipeline tho
thought it was trying to encourge camera stacking and not mov away from it
its a pretty common way to handle things like view models and not clipping geo
as opposed to having multiple camera's at once..
u can just stack renderers in teh asset
each doing a different thing.. and u can insert passes between the stuff thats already there
ya, i mean i still use it too.. but i heard that somewhere. could be misinformation
"renderer feature" is what i was thinking
i use this + layers to render an outline in one of my projects
yeah have used that for rendering outlines for interactables etc
or sometimes i just do it manually with my own render feature + render pass
How to switch moving tools in the 2019 editor
It's an advantage tho because they retain the lighting in the scene
Unlike before they implemented stacking
I don't want to use the rotator tool, but the move tool
In the 2021-Now editor it has a button to switch
ya, it seems theres multiple ways.. as u could use a singular camera, and have a certain layer render after everything else..
which would be equivilent to stacking camera's w/ different culling
but yup, many ways to peel a banana i suppose
afaik its the same.. Q W E R T Y are the hotkeys to swap thru the tools
u can find all ur shortcuts here in this menu, as well as modify them to ur liking
i have mine set to mirror Blender's transform tools
I have a coroutine in an OnTriggerExit2D method shown here:
{
if(!shipExited && other.CompareTag(WORLD_TAG))
{
shipController.ShipEnteredWorld(false);
StartCoroutine(WaitForShipExit());
}
}
private IEnumerator WaitForShipExit()
{
shipExited = true;
yield return new WaitForSeconds(0.25f);
shipExited = false;
}```
Every time I restart the level or stop playing the game in Unity, I get this error around 3-4 times:
``Coroutine couldn't be started because the the game object 'Collision Detection' is inactive!``
I have attempted to change my if statement to this: ``if(!shipExited && other.CompareTag(WORLD_TAG) && gameObject.activeSelf)``
And this has not fixed it, any recommendations? Thanks!
Right! Of course! Can't believe I forgot that. Thanks
physics methods run on their own..
meaning if the gameobject is inactive the updates and stuff stop.. but the physics methods wont..
so its trying to call the coroutine. when the coroutine cant run
if(!shipExited && other.CompareTag(WORLD_TAG) && gameObject.activeSelf)
Ah, gotcha, that makes sense
u could try this..
to make sure the gameobject is active when the physics methods try to run
wait.. u said u tried that?
u could also make a method to check if the coroutine is already running. to avoid calling it mutliple times.. but not sure thats the issue
I believe I did, that's why it was pretty confusing. Though, I am trying it now and it seems to be working. Unfortunately the error happens once in a while, so I just have to wait and see
yea theres other things like the method to check if its running that might solve all the issues
I was thinking there might be multiple instances of the script running
I might double check to see if that is the case as well
if(condition)
{
if (!IsCoroutineRunning(WaitForShipExit()))
{
StartCoroutine(WaitForShipExit());
}
}
private bool IsCoroutineRunning(IEnumerator coroutine)
{
return coroutine != null && coroutine.MoveNext();
}```
something like this.. but i dont know what it does.. just seen it in a unity forum
i had to look up what .MoveNext() was
seems like u got a grasp on it..
Hahaha, I will try to avoid that if possible. Not that it won't work, it just seems a little overkill maybe
Thanks for the help
ya true..
np, gl
the whole physics functions running on a disabled object had me stumped with my own issue a year or so ago
turned my hair gray b4 i figured it out
Lol, I never knew that happened, thought the physics function couldn't run if the object is disabled
yea i did too thats why i never thought to debug it
and i went looking for the solution in all the wrong places lol
it wasnt until i started seeing debugs from a disabled object i finally connected the dots
i started adding booleans to all my stuff that had physics
"allowDetection"
and i would enable and disable it in the OnEnable() Disable() functions
It seems like the physics function runs a few times, even after disabling or destroying the object when the scene unloads or loads. Like for example, I put StopAllCoroutines() in an OnDestroy() and OnDisable() methods, both still gave me the error. Though, I don't know whether that would fix it anyways
just a blanket fix.. so i wouldnt forget about it
ya, not sure why that is.. im not super good with coroutines and how they work
Me either
i can use them but not quite fully understand them
u may want to cache the coroutine and stop it directly
Imma head out and see if this issue is fixed, thanks for the heads up on the physics functions, I will have to keep that in mind
altho im not sure that would yield any different result
Not a bad idea
๐ good luck again
activeSelf is the wrong thing to check.
activeSelf tells you whether this specific game object is activated
It does not tell you whether its parents are activated.
And if any parent of the game object is deactivated, then every child will be inactive.
You want activeInHierarchy.
My intention is to make it so that the player can only "float" aka hold down the space bar for 3 seconds, and after that they need to wait half a second to do it again, but it like floats for 1 frame then poof
A deactivated object's components cannot receive physics messages, since that would require a collider to be enabled and active on the game object or a child of the game object.
And there's no way for a game object to be inactive yet have an active child
how can i unlock the free movement of a sprite attached to a gameobject to fully rotate and face the player instead of weirdly changing shape here is the pic of two of them they should bot face me they are both square sprites and both have the same script the one closer to me works fine and the other one doesnt heres a pic
its like its stuck to the log
"log"
this is false immediately after you start floating
so the if statement fails and the else statement runs instead
and you stop floating
your conditions are wrong
and yes it is a parent of the square
The game object is non-uniformly scaled.
This will cause distortion as child objects rotate.
If you can't make a model with the correct shape, then set it up like this
- Parent
- Cube
- Sprite 1
- Sprite 2
i mean the sprite that rotates corectly is not attached to the cube
its just an example
that the second one is stuck
https://hatebin.com/rlkkzogpdm Guys any idea on why it is not resetting positions of Player and Ball after scoring a goal? (Last method is what should reset positions, and it's being called in the Ontrigger Method) I've linked positions already in the unity inspector and linked Player gameobject too
Yes. It's weirdly changing shape because it's parented to a non-uniformly scaled object.
Don't do that. All of the parents should have a uniform scale.
i.e. all three scale values should match
Parent the cube to an empty object and scale the cube however you want
Do you have any proof that the trigger methods are working at all?
ye i debugged
Ive been stuck on this for like 30 minutes and chatgpt couldnt come up with anything either but
private void FixedUpdate()
{
Vector3 fwd = cam.TransformDirection(Vector3.forward);
Vector3 velocity = (ballHolder.position - ball.position) / Time.fixedDeltaTime;
if (ballGrabbed && !grabPressed)
{
ball.GetComponent<Collider>().enabled = false;
ballRb.velocity = velocity;
ballRb.MoveRotation(Quaternion.RotateTowards(ball.rotation, ballHolder.rotation, rotationSpeed * Time.fixedDeltaTime));
return;
}
ball.GetComponent<Collider>().enabled = true;
if (Physics.Raycast(cam.position, fwd, 5, layerToHit) && grabPressed)
{
Debug.DrawRay(cam.position, fwd, Color.green, 10);
ballGrabbed = true;
grabPressed = false;
}
}
this code works almost perfectly except for that when the ball is dropped and the collision of the ball is re enabled, because the button to grab the ball has to be pressed in order for it to be dropped, the second if method is immediately reactivated and it goes back to the first if method and keeps returning. I tried adding a delay between the re enabling of collsion and second if method but didnt work
okay but now comes the problem that the cube has its own gravity
so when i move it the name stays in place
i debugged ResetPositions @swift crag
Move the rigidbody onto the empty parent object
The collider can remain on the cube.
collider too?
Rigidbodies look at all of their child colliders, so it'll work fine
no
how do i make ithe condition be like if the DataTime floatDuration is equal to the ucrrent date or more.. in the future
The collider can stay.
flip the comparison around
i was trying to edit the code and i had a method that after scoring a goal it would reset the current scene. But i only wanted to reset positions, not the whole scene
you want to fail if the current time is past the float-end time
note that your variable name is not good here
"float duration" implies that it's a duration
but that's not what floatDuration stores
it stores a time
floatEndTime would be appropriate
That should make it clear that DateTime.Now < floatEndTime means "the current time is before the time we stop floating"
So that is executing?
Are you using rigidbodies for the ball and player?
yep
I bet you have interpolation enabled.
i have a collision detector to keep score, but it only works for the first one?
@swift crag on players/balls?
When you set the position of a transform, you're going arounds the physics system's back.
Yes.
Don't turn interpolation off -- it's just what's causing the issue to happen.
When interpolation is on, the rigidbody sets the position of the transform every single frame
(so that it isn't just moving during physics updates)
doesnt worok ๐
But this means that if you set the position directly, it gets overwritten instantly
You need to set the position of the rigidbody component directly.
it's on youre right
ye
I would suggest referencing the player as a Rigidbody2D as well
but shouldn't it work for ball at least?
show me what your code looks like now
No, because you grabbed the transform from the rigidbody, and then set the position of the transform
It's identical to what you're doing for the Player
both GameObject.transform and Rigidbody2D.transform give you the Transform for the object / the object they're on
for both players and ball
change GameObject Player to Rigidbody2D Player and then change Player.transform.position to Player.position
and you'll be good
yep
gonna need way more information. show us your !code at least
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
i see thanks, that's because interpolate is updating the position of the object is attached to?
Right. Now, it would still be suboptimal to set the position of an object with a non-interpolated rigidbody on it
private List<Dungeon> _dungeons = new List<Dungeon>();
private int _currentDungeonIndex;
private Dungeon _currentDungeon { get { return _dungeons[_currentDungeonIndex]; } }
the last {get {}} causes index out of range exception in editor, whats the ideal way to fix this?
the last {get {}} causes index out of range exception in editor, whats the ideal way to fix this?
is there a way i can make that get {} not get executed while in editor
or should i just add an if statement
I'm not really clear how that works out, actually
why is my rigidbody falling through the floor ?
i see
I'd just return null if there are no dungeons.
Look at your console.
ty @swift crag ๐
oh wait -- the second screenshot is the floor, isn't it
yes
the thing is i cant return null
because dungeon is a struct
make sure you've got a rigidbody
the console's empty
ah, then return default
This is kind of wrong
But if all you're doing is stopping it from throwing up in the editor, I suppose that's fine
hold on ill send all of the player componets's
i didn't know this was a thing, thanks
default is the default value a field gets, iirc
for reference types it's null
and for other types it's going to be things like zero
You have both a character controller and a non-kinematic rigidbody here. This is not correct.
okay i understand
i was using new struct() with default constructors on structs before
that what i was thinking too
this is way more practical
That also works, I think
or cleaner
I'm a little fuzzy on the intricacies there
ill probably change my movement script cuz its trash anyways
default is nice for generic methods
(although, it's also a little bit misleading for value types...)
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;
using UnityEngine.UI;
public class TileSpawner : MonoBehaviour
{
public GameObject tile1;
public GameObject tile2;
public GameObject detector;
public Text score;
int i = 0;
void Start()
{
score.text = "Score: ".ToString() + i.ToString();
}
void OnCollisionEnter(Collision col)
{
if(col.gameObject.name == "Player")
{
i++;
score.text = "Score: ".ToString() + i.ToString();
}
}
}
and here is all of it: https://paste.mod.gg/iszlhrlbsddm/2
A tool for sharing your source code with the world!
well, you have the same problem with the last condition
floatCooldown is probably in the distant past
you want to check if the time is greater than the time the cooldown ended at
So you're saying that this increases your score and updates the score text once
but doesn't do it afterwards?
yes
You should use Debug.Log(col.gameObject.name); to log what's hitting the collider each time
ye but i thought >= did the trick, if that doesnt work what can i try?
Does this object collide with the player again after the first time?
@polar acorn there are multiple of them
you didn't write >=
you wrote <=
that's less than or equal
this checks if the cooldown is not yet over
if there are many things you can collide with, each one is going to have its own score counter
and they're all going to say your score is 1 after one hit on them
So every time the player interacts with a new one, you want to overwrite the text with 1 again?
shouldnt the only one with a score be "Player" because of the if statement
You said there are "multiple of them"
Multiple of what?
and it should update becuause of the variable i thought
oh my bad
multiple collidable objects
and does each one have its own TileSpawner component?
yes
i had originally but i thought u meant i should change it
i just copied and pasted them
how can i disable a sprite renderer componet through code?
soo... like this?
looks pretty
Each one updates the text, and each one has an i of 1
Yes, that's what I envisioned. But this is still going to be wrong, since you set floatDuration = DateTime.Now.AddSeconds(3); constantly as long as you have space held.
ye didnt work
You need to detect when you start floating exactly once
ah i see
so i put it with getkeydown
Thank you, will do
Then a second condition should check when the player stops floating. It'll have two reasons:
- GetKey is returning false
- The float end time is reached
you'll need to split this into two if statements
one decides to start floating if GetKeyDown is true and all of the conditions are met
one decides to stop floating if GetKey is false OR the time runs out
I'm confused as why my bullet when spawned dosent shoot at my mouse direction. i have made a code like this in another project's the same way and it just works but here i get this issue```cs
public void Fire()
{
if (Time.time > timeTofire)
{
timeTofire = Time.time + playerData.FireRate;
Projectile newProjectile = Instantiate(projectile, projectileSpawnPoint.position, projectileSpawnPoint.rotation) as Projectile;
newProjectile.SetSpeed(playerData.ProjectileSpeed);
}
}```
i did this and it only logged for the first detector
what is SetSpeed?
I'm guesing that your projectileSpawnPoint transform is rotated wrongly.
how can we add ads in unity game
It's direction would be relative to projectileSpawnPoint.rotation
What's set speed do?
Maybe SetSpeed sets your speed in the +Y direction, but the spawn point's +X axis is pointing forwards from your ship.
in that case, you need to rotate the projectile spawn point so that it's pointing in the right direction
its this function im my projectile script, so i can set my player projectile speed in the weapon script.cs public void SetSpeed(float newSpeed) { speed = newSpeed; }
to check if this is the case, @teal elk , you can pause as soon as you spawn your projectile. and select the projectile in the inpector and look where it faces
please help im getting this error and i think its cuz i retrieved the bool from the other script incorrectly
How're you moving this projectile?
no, it's because you have no object reference at all
go to the first error -- the one on line 14
we need mroe context about your code
something on that line is getting used, but is null
You've expertly cropped out the line numbers
scr is null
oh i think i get what you mean now, how would I fix that?
here is how I'm moving it , i will try to look at which way the projectile is lookingcs void Update() { transform.Translate(transform.up * speed * Time.deltaTime); Destroy(gameObject, lifeTime); }
Look at the lines those errors are on. Something on those lines is null but you're trying to use it anyway
๐ 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.
a NullReferenceException falls out whenever you try to read a member from a reference typed variable.
The score should probably belong to the player, and it should update the score when it hits the other object
move it forward instead of up
how can i fix it cuz i wanted to get the bool value from another script
i fixed it, it works now
make it not null
if you spawn your bullet looking towards the mouse
that would go into the screen
wait i might be confusing with UE
looks like you forgot to assign a reference in the inspector.
Where do you assign a value to scr
Your projectile will move in the direction of the transform's up value.
can you show the 3 arrows of your bullet when you spawn it ? what does it faces ?
in the same script in the start()
I sent the wrong one.. i meant to send this. I was working on a Drawing Mechanic yesterday, where it sort of drops waypoints for the navmesh to follow as you draw..
i retrive it form my other script
it would be useful to look at the projectileSpawnPoint
you don't have to pause after shooting a bullet that way
the rotations will be identical
No, where do you set scr
its still very much a WIP and imma most likely need help today.. as i got to get these waypoints into the navmesh script.. w/ is pretty chunky and bad rn
still cool :)
