#๐ปโcode-beginner
1 messages ยท Page 291 of 1
One message removed from a suspended account.
that's also the same video as before
One message removed from a suspended account.
and press play before starting your recording.. we don't need to see the 5 seconds of play mode laoding ;p
this is the concept
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
Pause -> Play -> Start Recording -> Unpause (secret sauce)
no need for the pause in this case
lol, its my preferred method.. b/c ShareX takes ages to Initialize sometimes
Just depends if the issue happens on load or not
soo.. shun, are u following a tutorial.. or just making this as u go?
One message removed from a suspended account.
lol ๐ฌ
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
Vectors
so.. how come you chose your role as programmer then? ๐
One message removed from a suspended account.
One message removed from a suspended account.
so why are you even doing this?
here you are basically rotating the the camera on its X and Y axis
How can I check if an object is currently in a camera's field of view?
also dont multiply by time.deltaTime
You can try OnBecameVisible or whatever
in my variation i Only rotate the camera on the Y axis.. and then i rotate my CC object on its X axis
this seperates teh two rotations and makes it simple for my CC to just move the direction its facing
One message removed from a suspended account.
Ok thanks
so you are doing game dev
fun is objective ๐ (it def gets fun),
at the beginning not soo much fun (until it is)
can someone help me please. I am using Visual Studio 2022
I am trying to type the word private
but it wont let me.
what do i need to do
type it inside the class
I can tell you there is absolutely nothing 'fun' about game dev unless you are very dedicated to it
and not outside the } ending bracket of the class
im new man you got to explain more
One message removed from a suspended account.
You should only have members inside a class
everything else in that code is inside the class's { } brackets
im following this guys video but he opens visual studio code and his base code is differnt from mine.
ok yeah when he opens code his bracket is right there always
And fix your errors before continuing
It isn't going to help if you try to write code when your code is broken
holy shit my code is broken in the beginners code section?? who would of thought

please stop talking if your not going to help
Start with the other error before trying to add to your code
He's helping you
when he opens visual studio code his code ends here at the bracket you highlighted
i got a bunch of other shit in my code
my code doesnt even have that bracket
You're putting the "other shit" in the wrong place
you have to add and remove brackets as u need them
fixing error is part of help
would be a great idea for you to go and learn what a class is, a method, their signatures ..etc, the basics, so these mistakes aren't made anymore and you can fix them yourself
You should not put other shit below that closing brace
this is what i mean
not a good plan
Nor the character immediately after that
there is no plan. I want to know my scripts start with 9 extra lines of code
They've either edited their default script template, or deleted it in the video and you missed/ ignored it.
It doesn't take any coding knowledge to work out how to get your class in the same state as theres -> delete the extra code
i am copying this guys script exactly
One message removed from a suspended account.
and i cant even type the word private
bet?
you weren't copying it exactly, otherwise you woudln't have the mistakes you had
No you are not. @polar acorn increase the counter
Make sure you're aware of what Steve has pointed out (the extra {})
blocked
the tutorial doesn't have this line
trying to copy it... cant type the word private because im typing in the wrong spot...
because my fucking code template is different...
so.... fucking delete the extra code ๐
There are other errors in the file. You will not be able to consistently type private until you fix them.
its teh exact same.. delete the stuff in the middle!
your template is the default template that everyone has
terrible help
you have a game object with a collider
and then i did GetComponentInParent
but i get what your saying
would it still like detect the object
these two scripts are the exact same
or only in the parent od that collider
What does detecting the object have to do with get component in parent?
I did it exactly like the tutorial so why does theirs work and mine doesn't" counter:
Number of times it wasn't exactly like the tutorial: 153
Number of times it was exactly like the tutorial: 5
Number of times the code literally did not exist: 1
2022-07-19 to 2024-4-05
lol im sorry i didnt write the word trying in my sentence
im am TRYING to copy his code
calm
ill go back to learning and you guys can go back to whatever the fuck your doing
thanks for helping
pretty much im asking if GetComponentInParent also does GetComponent
the docs I linked to tell you
yes it does
yeah but its quicker to ask
alright thanks
at very least put effort to research things
I have no idea why you decided to go off at me for trying to get you to fix the errors that caused the problem you were interacting with. Nobody can help you if you think everyone's out to get you. It was only after you were hostile to everyone's help did things truly go to shit
in the 3 mins between me posting the link, and someone actually answering.. you could have read it in the docs 50 times
its kind of hard while trying not to get hit by a car
coin toss tbh
lol, dodging traffic and learning unity?
i want to know before i get home
lmao
so i dont have to waste time
if i was on my pc fair enough
iโd look through the docs first
I mean, you're typing in and reading Discord.. you could have just googled it and read the docs
download the whole unity API into your phone 
theres a difference between trying to read paragraphs and a short sentence
real
it's a short sentence in the docs ๐
Not sure you can really use offline docs on a phone, but maybe there's some sort of reader for stuff like that
yeah I use it often
On a phone?
smart
Huh, does the site just work straight from files or something
they are just html files
im guessing its like a pdf
or that
Yes, I'm just surpised phones can navigate that properly from their weird-ass file systems
But not entirely unexpected. Good to know
Your reply was not helpful at all. You told a new guy who knows his code is broken that his code was broken. you offered nothing of value.
You virtue signaled a reply ( akin to saying, you didn't learn like i did. Not good enough)
bro stop crying and listen to these people
theyโve been helping here longer than u were alive
please stop crying
ya need to learn general code and scripting before touching unity
im pretty sure they are right
dude uses "virtue signaled", fucking red flag if I've seen one
unity isn't easy to just jump into with little coding knowledge
and if u didn't notice Vertx is a Moderator.
funny to tell the moderator to stop talking
in his own discord
lol
how come you've got the insert toggle on??
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using static scr_Models;
public class scr_CharacterController : MonoBehaviour
{
private DefaultInput defaultInput;
public Vector2 input_Movement;
public Vector2 input_View;
private Vector3 newCameraRotation;
[Header("References")]
public Transform cameraHolder;
[Header("Settings")]
public PlayerSettingsModel playerSettings;
private void Awake()
{
defaultInput = new DefaultInput();
defaultInput.Character.Movement.performed += e => input_Movement = e.ReadValue<Vector2>();
defaultInput.Character.View.performed += e => input_View = e.ReadValue<Vector2>();
defaultInput.Enable();
newCameraRotation = cameraHolder.localRotation.eulerAngles;
}
private void Update()
{
CalculateMovement();
Calculate_View();
}
private void Calculate_View()
{
newCameraRotation.x += playerSettings.ViewYSensitivity * input_View.y * Time.deltaTime;
cameraHolder.localRotation = Quaternion.Euler(newCameraRotation);
}
private void CalculateMovement()
{
}
}
all youve told me is this is not the place to come for information
ill see you guys later
its not.. its an optical illusion.. its just a fat ass cursor
You have likely accidentally duplicated this script
why do people get aggressive when they lack knowledge of something, but always take it as "talking down to " or whatever when suggestions come
If your IDE is not generally underlining errors in red and giving you proper autocomplete you also need to configure it. !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
can't lose it that way, I guess!
Yes, people do not take well to bullies like you. Bye
ya, other than just trying to make it being visible during tutorial videos and stuff.. its quite annoying when i accidently Do turn on insert
They left, and there was peace in the land
these are my only 2 scripts
but for how long
yeah, you say that, but what about this
are you trying to use regular fields in a static function / class?
scr_Models.cs was outside of the Character folder, I've got that into Character folder just a few seconds ago
Can you check again?
jesus
Then try restarting Unity
based
its the go-to when nothing makes sense ๐
did you not save ?
I did save scripts, nothing else was changed in the scene
cause the bottom errors dont make sense
cs0708
It all stems from the one error that has now been resolved.
ah ok myb
I have entered safe nerd mode cause apparently the issue hasn't been resolved, or it's not related to Unity being buggy
Is the first error still there? If it's gone then you can start trusting the other errors
It looks like your scr_Models script file tries to redeclare scr_CharacterController
Start from the top. You have two scr_CharacterController classes
did they show scr_Models script?
using System;
using System.Collections.Generic;
using UnityEngine;
public static class scr_CharacterController
{
#region - Player -
[Serializable]
public class PlayerSettingsModel
{
[Header("View Settings")]
public float ViewXSensitivity;
public float ViewYSensitivity;
public bool ViewXInverted;
public bool ViewYInverted;
}
#endregion
}
well there u go
What is any of this
same name of class
Well there's your problem, why does scr_CharacterController exist in scr_Models
Oh I just noticed that
filenames and class dont match, sweet
it just froze my phone lmao
was about to say cause it wasnt declared as static in other file
- Class name you're already using
- Static class that has non-static things in it
- Class inside of a static class
This is just very wrong
really? are you on android ? thats what I use
prob. I have custom app for reading html properly so links work
iphone doesnt let u mess with files easily
You can have classes declared in static classes just fine, no?
Haven't checked but that should compile, the general issue is just the class name collision
Presumably the actual character controller is a non static MonoBehaviour and all the other errors are trying to resolve some imaginary partial class amalgam of these two
Also why the scr_ prefix? If you want to categorize classes by their purpose, use namespaces
what does scr even mean? Script? -> pointless
It's just gonna be a pain later on when you have 20+ scripts all starting with the prefix
for me It buggs me when people even do SomethingBase for base classes 
๐
ECS development is suffixtown
Yes but it certainly indicates they're doing something wrong
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using static scr_Models;
public class scr_CharacterController : MonoBehaviour
{
private DefaultInput defaultInput;
public Vector2 input_Movement;
public Vector2 input_View;
private Vector3 newCameraRotation;
[Header("References")]
public Transform cameraHolder;
[Header("Settings")]
public PlayerSettingsModel playerSettings;
public float viewClampYMin = -70;
public float viewClampYMax = 80;
private void Awake()
{
defaultInput = new DefaultInput();
defaultInput.Character.Movement.performed += e => input_Movement = e.ReadValue<Vector2>();
defaultInput.Character.View.performed += e => input_View = e.ReadValue<Vector2>();
defaultInput.Enable();
newCameraRotation = cameraHolder.localRotation.eulerAngles;
}
private void Update()
{
CalculateMovement();
Calculate_View();
}
private void Calculate_View()
{
newCameraRotation.x += playerSettings.ViewYSensitivity * input_View.y * Time.deltaTime;
newCameraRotation.x = Mathf.Clamp(newCameraRotation.x, viewClampYMin, viewClampYMax);
cameraHolder.localRotation = Quaternion.Euler(newCameraRotation);
}
private void CalculateMovement()
{
}
}
UnassignedReferenceException: The variable cameraHolder of scr_CharacterController has not been assigned. You probably need to assign the cameraHolder variable of the scr_CharacterController script in the inspector. UnityEngine.Transform.get_localRotation () (at <17484a9af6b944dea5cd9be4dbb0da2c>:0) scr_CharacterController.Awake () (at Assets/Scripts/Character/scr_CharacterController.cs:23)
I did assign it
It looks the variable cameraHolder of scr_CharacterController has not been assigned.
You probably need to assign the cameraHolder variable of the scr_CharacterController script in the inspector
It's right here
Then there's probably another instance in the scene
Try searching your hierarchy for t:scr_CharacterController
It has its uses, the entirety of LINQ is based on that. Static Enumerable class that stores extension methods and private iterator implementation classes
It's just the Player, nothing else has scr_CharacterController besides the Player
Can you show your hierarchy with that search input? While the game is running after that error has popped up?
The error somehow disappeared?
:sus: soo.. fixed then? lol
thanks ๐ค
Much like the Emperor, somehow returning
public GameObject slime;
private GameObject player;
private Transform playerPos;
public int slimeToSpawn;
private Vector3 position;
float TimeT = 0;
bool spawned = false;
public int minX;
public int maxX;
public int minY;
public int maxY;
public string buttonName;
private void Start()
{
player = GameObject.Find("MC");
playerPos = player.GetComponent<Transform>();
}
private void Update()
{
if (!GameObject.Find(buttonName))
{
TimeT += Time.deltaTime;
if (slimeToSpawn > 0 && !spawned)
{
position = new Vector3(GetX(), GetY(), 0);
SpawnSlime();
slimeToSpawn--;
spawned = true;
}
if (TimeT > 1)
{
TimeT = 0;
spawned = false;
}
}
}
private void SpawnSlime()
{
Instantiate(slime, position, Quaternion.identity);
}
private float GetX()
{
float x = 0;
do
{
if (Random.Range(0, 2) == 0) x = Random.Range(minX, maxX);
else x = Random.Range(minX, maxX) + 0.5f;
} while (playerPos.position.x - x < 2 && playerPos.position.x - x > -2);
return x;
}
private float GetY()
{
float y = 0;
do
{
if (Random.Range(0, 2) == 0) return Random.Range(minY, maxY);
else return Random.Range(minY, maxY) + 0.5f;
} while (playerPos.position.x - y < 2 && playerPos.position.x - y > -2);
}
I made that code to instantiate a gameobject every second at a different location and it has to spawn away from the player, I made a prefab for the slimespawner, the first object of the prefab works, the second one spawns 3 slime at a time for five time, so he decrements slimeToSpawn once but spawns 3 objects
These are the 2 different objects
!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.
https://paste.ofcode.org/3aBxksJzQ9jZ5MFyxCEaykM
My code destroys a game object but apparently this same script tries to access the destroyed gameobject again (but the last time it is mentioned is when it is destroyed), what could be the issue? The error stems from the breakwoodwherenecessary() function
Is there a way to check if a ui element is being masked?
you destroy the game object, but don't remove it from the list
do a reverse for loop, and remove the index after destroying the object
am i doing something wrong? (i mean cleary i am)
the audio manager is in another scene and im trying to call him out from another scene
audioManager = FindObjectOfType<AudioManager>()
Or make AudioManager a singleton
Awake is ran once, so maybe Awake on this is ran before the audio manager exists
but you haven't actually said what the problem is
You cannot do cross-scene reference
you need a singleton for that
sorry any way you can elaborate, never did a reverse for loop
do forr in vs then tab
and it's a keyphrase that you can google to learn more about it
thanks, i get the logic behind it but im not sure how it will work, would it be nested within the other for loop?
no, replace it
a reverse loop starts at the end, and works towards the beginning, this allows you to remove items from a list as you go
doing a forward loop causes issues if you remove items
so aswell as destroy .remove()?
destroy gameobject
remove index
ohh okay
how comes that doesn't work when counting up (if i need to remove the list index value myself)
because you change the count
ill check it out thx
first time round loop, index 0.. -> destroy object, delete index
element 1 is now element 0, second time round loop is now checking index 1, so what's now in 0 has been skipped
here is more info with examples if you need
https://unity.huh.how/references/cross-scene-references#resolution
https://gdl.space/yowuyewuxi.cpp
I made that code to instantiate a gameobject every second at a different location and it has to spawn away from the player, I made a prefab for the slimespawner, the first object of the prefab works, the second one spawns 3 slime at a time for five time, so he decrements slimeToSpawn once but spawns 3 objects
These are the 2 different objects
the first object of the prefab works, the second one spawns 3
this isn't clear. Do you mean SlimeSpawner works fine, but SlimeSpawner (1) doesn't?
yep
ohh okay, so as the items will be moving towards index 0 when being removed, iterating reverse allows you to still check the remaining items?
if it were reverse you could miss some
starting at max, say, 9.. then removing 9.. the other elements don't change position
sure
reference is always appreciated
i've run into "unity how" in the past, i didn't know they had a topic about cross scene too
yup, most of the stuff is there. Its made by a mod here
THANK YOU @hexed terrace it works
what do you mean? what part of the code?
that was obvs not a reply to you
oh rly?
i didnt know that, thats cool
who is the mod just by curiosity
yeah but I didn't understan, so what's the issue you think?
didn't understand what?
I've no idea what your issue could be
oh, alr ty anyway
someone please?
vertx
thanks
if you disable the spawner that works, what happens with the second spawner
that actually sounds kind of interesting but I already turned off my pc, I will for sure try it tomorrow
You need to try different things to troubleshoot the issue.
The second spawner has the issue, so remove the other from the equasion and then work out the next move
Is there a interface similar to IPointerEnterHandler that will get called every frame while an element is hovered?
IPointerStay
or something
ah no
you need two bools and use Update probably
How do I stop friction on the side of things, because whenever I jump to the side of something, it can just stick like this
do a boxcast in that direction, if its blocked dont apply force
i suppose you can try the no-friction material thing
but its a crapshoot half the time
if i were to do the no friction wouldnt i just slide everywhere on top of the platform
not if you got drag
Hi guys i accidently deleted something from my assets that i didnt know what it did, now background is purple. Anyone have any idea? it was a "material"
It was the material that was on the background. Select it and put another material on it.
Also not a coding question
anyone with experience using scenereference know how I can reference a scene using an onclick unity event? ie I want to select one here
the function that takes in a scene doesn't appear
Scene isn't serialized type
no chance
string is your best shot
or int (build index)
so no real point using scenereference then
since you could just load it by index anyway
does anyone know how to make a clickable button in game (fps, so no cursor)?
i'm making a grapple game
clickable button as in Keyboard ?
or you mean physical world button
no like a textmeshpro button
yes
make it a mesh no ?
Ima be honest using VS code is kinda pissing me off because im creating a game and every time i open a new C# script it redownloads itself when i had just installed it.
you can use world canvas with button but you have to modify the Input module to work with fps view (locked cursor)
aight
what redownloads itself?
VS Code
from where?
i never seen on any pc an app downloading itself lol
unles like a virus ig
ike every time i open it, I see the set up window for Microsoft VS Code
and it puts me through the set up
have checked the "dont show next time"
or watever
which setup you speak of
this one
weird. Try installing for All Users?
I have no idea why it would keep showing that unless you clicked the intaller yourself ๐คทโโ๏ธ
Nope, I have a desktop shortcut for it and for some reason it doenst seem to detect that I have it installed
It doesnt even open my script after "downloading" it
How do I find which UI element is closest to the center of the screen?
What is the difference between a C# (automatic) property and a public variable?
many things
for starter one is a field and ones a property
property is like a method that runs every time you change it or access the variable
find the center pixels coordinates and subtract every gameobjs postion relative to that pixel
How does it "run"? Could you give an example please?
oh didn't see edit your wrote "auto"
like get;set; just as is
not much diff i suppose
Right now, not much difference seems like no difference
That's what I was doing but it wasn't working... Maybe I'll try making the distances absolute values.
well if u write it like that kinda defeats the power of properties
get' and set are very powerful to use
Been doing C++ and came back to C#. Not used to stuff doing loads for you with a couple of keywords like this
What if I want an event to happen every time I set a value ?
anybody know how i can do something like this to make it work? GameObject objectCanvas = GameObject.Find("Object") || GameObject.Find("Other Object");
use serializefields
gameobject.find one of the wrose methods to use
Ah cool. That sounds cool. Where do you define the body of the property, aka the code that runs upon change
private string _name;
public event Action<string> NameChanged;
public string Name
{
get { return _name; }
set { _name = value; NameChanged?.Invoke(value); }
}```
serializefields to look for a string? can i look for multiple strings for one variable?
no for your references.
You should not be using strings to find objects
that is brittle and error prone
plus very slow
oh do object references?
Sorry, not understanding what you mean. Missing vital info in your question.
As navarone said, avoid using GameObject.Find. It's bad because:
- A name is not a reliable value, it's just a string value that is not unique, meaning you can end up with dupilcates.
- An extension of 1. The method doesn't tell you there's duplicates if there are, it just returns the first one it finds. Terrible for debugging.
- I've heard that due to the fact it searches every gameobject it isn't performant
for example [SerializeField] GameObject theObjectYouWant
kk, ty, ig ill just switch out of Find
Better to break bad habits early
yep
i just started and am watching a tutorial on how to use unity and i made a cube jump but the cube is supposed to jump higher when i hold jump any ideas why it isn't
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
[SerializeField] private Rigidbody2D rb;
[SerializeField] private float jumpForce = 10f;
[SerializeField] private LayerMask groundLayer;
[SerializeField] private Transform feetPos;
[SerializeField] private float groundDistance = 0.25f;
[SerializeField] private float jumpTime = 0.3f;
private bool isGrounded = false;
private bool isJumping = false;
private float jumpTimer;
private void Update() {
isGrounded = Physics2D.OverlapCircle(feetPos.position, groundDistance, groundLayer);
if (isGrounded && Input.GetButtonDown("Jump")) {
isJumping = true;
rb.velocity = Vector2.up * jumpForce;
}
if (isJumping && Input.GetButtonDown("Jump")) {
if (jumpTimer < jumpTime)
{
rb.velocity = Vector2.up * jumpForce;
jumpTimer += Time.deltaTime;
} else {
isJumping = false;
}
}
if (Input.GetButtonUp("Jump")) {
isJumping = false;
jumpTimer = 0;
}
}
}
Does it make get and set methods (GetCarNumber, SetCarNumber... etc) redundant?
!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 instead I'd just need that as a property with { get; set}
What?
read this #๐ปโcode-beginner message
yeah but I still prefer methods some times
the drawback of using properties in unity is they are not serialized in the inspector without a special attribute
post the code properly by using one of the links
reading code like that in the discord chat is a pain
esp on mobile
ok i will im sorry
I think I'll just use it all the time, if I encounter a time when I need to use methods, I use it then
Thanks navarone
how do i use this?
You read it
You click a link
You copy your code into the website
You click save
You copy the changed url
You paste that url here
Yep
Thank you
im watching a tutorial and i got the a square to jump but its supposed to jump higher when i hold jump
The second if was likely supposed to be GetButton not GetButtonDown
If it WAS supposed to be GetButtonDown, then the tutorial is wrong
Thank you !!
It works perfectly thank you so much !
No prob. Just to clarify, GetButtonDown is only true for the single frame when you press the button. GetButton is true as long as it is pressed
Another quick question about C# properties. Is it good practice to declare them and not leave them to default values? Even if it's an automatic property.
you mean assigning value on initializer ?
So for example
public int CarAge = 10;
I could just write ```cs
public int CarAge;
thats an error
yes
you dont have to assign values
especially to value types
they all have defaults
Isn't that bad practice?
say i have a dictionary/list of a custom class- is there a way to instantiate a gameobject with that component, not just a clone of it? and can multiple gameobjects have that same compenent? (again, not just a clone, but a reference to the single component in the master dict/list)
it really depends I think.
Problem with automatic ones, it sort of forces you to use a default value
I am using it with bools
im blanking on c#, does setting an array = to another do a deep or shallow copy
you're copying reference types
its the same object
sharing the same address of same house
so array.copy is needed
Btw for this, it doesn't. I was confused on the syntax
All makes sense. Thanks
yeah non require you to assign when declared
unless it was like a const
What I meant is I can write
public bool GameIsPaused
{ get; set; } = true;
``` assigning it true on declaration to avoid ambiguity of defaults
yeah ig. if you don't then its false no biggie
that's what happens with serialized fields, you can, for example, have one "Game Manager" Singleton class in one GameObject in your scene, and for each component/script you want to reference this exact gamemanager instance you drag that GameManager into the serialized field into the editor.
i wouldnt make GameIsPaused public set though
good/bad practices considering
even if i have multiple master components? I understand and use the game manager concept, i.e. audio handler, etc, but if it's many of the same class does it still work?
and i need to do it programmatically (? is that a word?) not via dragging
would i just do something like:
obj.addcomponent<componentthatneedstobeadded>() = reftomastercomponent;
oh I think i see what you mean, there is a much simpler solution then
basically if i instantiate multiple objects with a component set to the master component, if one changes, will they all change
i am not great at phrasing questions
and if thjat one changes it will change all of them, yea?
There is only one
say you have a component <Enemy> and you want each enemy to hold a reference to <EnemiesMaster> or whatever, but you create them at run-time, so whenever you instantiate an <Enemy> you can A. pass it the reference then B. create a prefab where you can have a serialized field (assuming that the master is placed in the scene and probably should)
let me explain my problem with the context, i think that may help
You don't need to copy the component to every instance, you just need every instance to reference the single original component
I have a bunch of samples that the player needs to analyze, and each sample is unique. you can have many of these samples at once, i.e. you can have 4 sample#1s, but the sample itself contains data on whether it's been analyzed or not, and if they have analyzed sample#1 then it should reflect in each of the sample copies as well
by itself? no, a given object has no idea what holds a reference to it (unless you implement that), so once you destroy/disable whatever they referenced, you will get an error when trying to call it's function or get any value
i want each of these sample copies to have the same sample object, not copies
the sample object that is held in a dictionary
so like if there's a code on the instantiated object that's like
public void initializesample(sample ourSample){ //oursample would be sent in like so: initializesample(masterSampleDict[sampleneeded])
sample = oursample;
}
would this accomplish that
Yes
ok, thank you
i'm trying to get better with phrasing ๐ญ
I think some languages handle references differently and I always forget which ones do what
Just give it a guess first, see if it is a reference or not, i often just try-and-error, you can have some hilarious bugs on the way, just play with it and see what happens! Best way to learn for me, maybe not the most "optimal" but what the hell, make it fun
thanks, haha, I'll work on that more too
Hey, I'm trying to create a second path in my class, but I can't work out how to reference the other path in my movement script - is it possible without changing the whole code?
public bool pathOne, pathTwo;
public static Transform[] points;
// Calculating the length of the path
public static float totalLength = 0;
public int calculatePath = 0;
void Start ()
{
if(pathTwo)
{
points = new Transform[transform.childCount];
for (int i = 0; i < points.Length; i++)
{
points[i] = transform.GetChild(i);
}
}
else
{
points = new Transform[transform.childCount];
for (int i = 0; i < points.Length; i++)
{
points[i] = transform.GetChild(i);
}
}
PathLength();
}```
How it's being referenced ```void GetNextWaypoint()
{
if (wavepointIndex >= Waypoints.points.Length - 1)
{
EndPath();
return;
}
//furthestOnPath += 10f;
++wavepointIndex;
target = Waypoints.points[wavepointIndex];
runBack = false;
}```
Such as another Waypoint object with its own set of points?
Then make yourself a List of Waypoints and reference by index, or just declare two WayPoints:
public Waypoints Waypoints1;
public Waypoints Waypoints2;
Yeah. So Waypoints pathOne/pathTwo is set in the inspector
Thanks very much! I'm giving this a go now.
Get rid of the static keyword from your points of transform else each instance will be using the same points
anyone know, why it wont allow me to drag the UI elements to my Script Fields? It just shows a back circle with a slash through it, but ive tried both with Text and Textmesh pro, for the text field, and now its not allowing me to do any buttons or input fields either?
those are default reference fields which is usually for debugging. You should be inserting it directly into the object on the scene itself
And you can't reference scene objects from outside the scene
yeah, if it lives in your assets, it must be part of some instance like a prefab
oh thank you i forgot to make a game object for the script so that makes sense
I'm not sure how to translate what you said into my script... Sorry. In Unity, I have the Waypoint script on the parent object and enemies are spawned in, can I not make them reference the "pathOne" bool to follow those sets of waypoints from GetNextWaypoint()
Depends how you want to structure this thing. Do you want this WayPoints class contain two (or more) different paths, or should WayPoints contain a different path each.
If you want to add all paths to a single WayPoints class then you need an array of points for each path such that:
public Transform[] pathPoints1;
public Transform[] pathPoints2;
Then for your method you can make a secondary such that:
void GetNextWaypointFromPath1()
void GetNextWaypointFrompath2()
Or if you make a List/Array of path points then you can make a method such that
void GetNextWaypointFromPath(Transform[] points)
You also need some indicator for what path you want to use, but I wouldn't suggest using a bool since that only restricts you to two different values
Thank you very much for that. I'm trying to be flexible for a tower defense game, I was hoping that I could set a "startpoint" and then the enemy would follow the path that is made up of those child items. I'm being a total beginner by using bools to just set pathOne/Two/Three, as/when needed... In hope that I don't have to edit all of my prefabs
I'm controlling the spawnpoint when I want to use a different point like this, so I am trying to set a bool which could tell the enemy the path as well foreach (EnemyBlueprint enemy in wave.enemyWave) { if(enemy.enemySpawn != null) { spawnPoint = enemy.enemySpawn; } else { spawnPoint = defaultSpawnPoint; }
Generally you choose Array.Copy or Buffer.BlockCopy for this.
.Clone is an ancient api predates back to framework 1.x
ah yeah when i needed my usecase is simple so i do copy. I just recall that was also a method, didn't know it was that old though lol Good to know
When testing, if I set the pathTwo bool & remove the other reference, the enemies will walk along the second path. I think I'm trying to do it the other way you mean, by having waypoints containing a different path each. I guess, with that method, I need to create an array and either count child objects or drag each waypoint into the inspector?
A single WayPoint class is useful if you have a single instance such that it's the manager of these waypoints that all enemies reference. So, each enemy would only need to ask the manager for the path they are assigned to. The multiple different waypoint instances of the class that contains a single path each is useful if you do want to have a single array of waypoints per enemy, such that each enemy would be assigned an instance with a specific (or unique) path to follow.
I'd usually prefer the first solution, and just have all enemies grab from the manager as that's a lot less arrays of points you need to be instantiating.
My player seems to be glued in place. It's like trying to convince a cat to take a bath. Is there anything wrong with the code?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using static scr_Models;
public class scr_CharacterController : MonoBehaviour
{
private CharacterController characterController;
private DefaultInput defaultInput;
public Vector2 input_Movement;
public Vector2 input_View;
private Vector3 newCameraRotation;
private Vector3 newCharacterRotation;
[Header("References")]
public Transform cameraHolder;
[Header("Settings")]
public PlayerSettingsModel playerSettings;
public float viewClampYMin = -70;
public float viewClampYMax = 80;
private void Awake()
{
defaultInput = new DefaultInput();
defaultInput.Character.Movement.performed += e => input_Movement = e.ReadValue<Vector2>();
defaultInput.Character.View.performed += e => input_View = e.ReadValue<Vector2>();
defaultInput.Enable();
newCameraRotation = cameraHolder.localRotation.eulerAngles;
newCharacterRotation = transform.localRotation.eulerAngles;
characterController = GetComponent<CharacterController>();
}
private void Update()
{
CalculateMovement();
Calculate_View();
}
private void Calculate_View()
{
newCharacterRotation.y += playerSettings.ViewXSensitivity * (playerSettings.ViewXInverted ? -input_View.x : input_View.x) * Time.deltaTime;
transform.localRotation = Quaternion.Euler(newCharacterRotation);
newCameraRotation.x += playerSettings.ViewYSensitivity * (playerSettings.ViewYInverted? input_View.y: -input_View.y) * Time.deltaTime;
newCameraRotation.x = Mathf.Clamp(newCameraRotation.x, viewClampYMin, viewClampYMax);
cameraHolder.localRotation = Quaternion.Euler(newCameraRotation);
}
private void CalculateMovement()
{
var verticalSpeed = playerSettings.WalkingForwardSpeed*input_Movement.y*Time.deltaTime;
var horizontalSpeed = playerSettings.WalkingStrafeSpeed*input_Movement.x * Time.deltaTime;
var newMovementSpeed = new Vector3(horizontalSpeed, 0, verticalSpeed );
newMovementSpeed = transform.TransformDirection(newMovementSpeed);
characterController.Move(newMovementSpeed);
}
}
Consider pasting your code to a pastesite
Awesome. With that said, my logic wants to create an array of paths in the scene and then send the enemy down that path. I'm happy with it being an array since it will be flexible and I can hold the position in an Int in my "spawn" code... If that logic works?
Sure, arrays work
remove that collider, and paste your code to a proper website for better reading
!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.
why does the player do this as soon as i put animations it stopped working
You should be more descriptive with your questions.
Assuming you're referring to the character pose, this is the default humanoid pose when no animation is playing.
Not code related too.
Yeah my bad it appeared that i didnt have my animation on humanoid thats why it didnt work
Hey I'm trying to make a multiplayer game with the help of a tutorial using photon..
Everything works fine if there is only one player present in the room but as soon as there are two players in the room.. controls just get swapped.
I control the other player's character and vice versa.
Can anyone help
probably did not follow tutorial correct or its bad tutorial. also#archived-networking
There were only one issue while following the tutorial that when I was dealing with Main camera mine had some errors saying I'm trying to inherit Component.Camera so I changed the name..which works for single player
But again in two players I control other player
https://paste.ofcode.org/f3tgpHFMG32KFRzwB4HCW9 The Player recoil dosent seem to be working when i attack.
you overwrite velocity every frame
where do i do that? is that with the private void Move()
yes. just like you are preventing Move from being called for the duration of your Dash, you need to do the same for the duration of your recoil if you want it to work correctly
so if i did if(pState.RecoilingX || pState.RecoilingY) { return}; would that work hypothetically?
dosent seem to work
any other ideas?
you didn't bother providing any details about what isn't working about what you tried
i added if(pState.RecoilingX || pState.RecoilingY) { return;} this line right under dash, after i hit player movement freezes because pState.RecoilingX or Y depending on where i hit it from stay active
and why do you think that is?
give me a second to look through it again
there are no references to my void Recoil()
wait no
thats not it
is it?
well that's obviously part of it. but you also need to rethink the order of operations
is it based on where my return is?
read through your logic and figure out when/where you change certain variables and under what conditions you change them
ok give me a sec
ok wait, isnt it as simple as adding Recoil(); to update
let me try that
tried it it seems to be working
im stupid
@slender nymph hey im sorry for tagging im not sure if im supposed to but i checked about object being centered and it looks right to me and also pivot point looks about right?
what object is that code rotating
you could show what object is assigned as playerTrans if you are unsure
but if it is rotating that root object, then make sure that the parent of the object shown in the video is also centered on its parent. and set your tool handle to Pivot instead of Center so you actually see the pivot point of your objects instead of the averaged "center"
aight i will try that thank you so much i will not spam you anymore haha ๐
!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.
The code: https://gdl.space/nazetihoda.cs
The Problem: The purpose of the script is that every time an object is added to the parentObject, it should save the name of the object in the list of prefabNames in the PlayerPrefs way, But the name is not added...
Hey guys I have a question, how can I get an object position without caring about the parent it's in?
Like if I put an object as a child it transform changes but how can I ignore this feature if I'm getting an object position?
for starters "Assets/Resources/Items/ProfileItem/" will not exist in a build for the LoadPrefabsFromFolder method
and for the love of god please don't save this data to playerprefs. it's bad enough that you are saving data based on the name of objects, please don't bloat the registry with that data.
can you provide some context for what you mean by this?
ah?
I have to keep it there, there is no other way.
why
I'm trying to make some kind of inventory system for profiles
And I need the data to save forever
and why does that require you to save this data to playerprefs?
you can write it to a file in Application.persistentDataPath
Well I want to get an object position and check if the player is clicking on its left or on its right.
The issue is that all the calculations are messed up since this object that I'm getting the position from is a child of another object so its transform position gets modified to the parent position and not to the world position anymore
it's transform.position property is the world space position
I know but PlayerPrefs is more convenient for me
Why are you so against it? ๐
because you're trying to bloat users registry with useless data that should just be written to a file so that nobody has to go through and clear that shit out of their registry using sketchy tools or by looking manually
at least if you save it in AppData it can just be deleted from the file system easily
you're also going about saving this data in a very not good way. saving the string names of the gameobjects is silly. try looking into a tutorial for how to properly set up save data
Because I tried to create my own way, save the names and then search for them in the folder to add them
yeah that's not a good system
and it won't even work in a build considering that folder with all your prefabs won't exist in a build
This is for a start
and it is incredibly flawed and should be scrapped so you can start over and do it right
you will have to completely redo this if you want it to work in a build, so attempting to get it working as just "a start" is not going to be beneficial since the entire system will need to be scrapped for something that works
Wow, I didn't know it was like that, so which system should you use?
This is what I learned in YouTube tutorials
what tutorial
How can you make a browser open a link in code? Is that possible?
Application.OpenURL
Hey, guys! I have a small issue with my game here. So, when I am collecting the power ups and trigger the particles and I pause immediately and move to settings and then coming back my power ups particles and other particles are disappearing. I have my code to share with you if you can to provide some useful information in order to help me fix it please do it.
Go back to main game from settings method
{
AudioManager.Instance.PlaySound(pressButtonSoundAudioSource, pressButtonSoundAudioClip);
StartCoroutine(GoBackToGameButtonAfterDelay());
}
IEnumerator GoBackToGameButtonAfterDelay()
{
yield return new WaitForSecondsRealtime(goBackDelay);
RoundManager.Instance.currentState = GameState.Pause;
optionsMenu.SetActive(false);
SetObjectsActive(true, true, true, true, false, false, true);
foreach (GameObject treeLog in treeLogsList)
{
if (treeLog != null)
{
treeLog.SetActive(true);
}
}
foreach (GameObject gemParticle in gemParticleList)
{
if (gemParticle != null)
{
gemParticle.SetActive(true);
}
}
foreach (GameObject powerUp in powerUpList)
{
if (powerUp != null)
{
powerUp.SetActive(true);
}
}
foreach (GameObject powerBoostListParticle in playerPowerBoostListParticle)
{
if (powerBoostListParticle != null)
{
powerBoostListParticle.SetActive(true);
}
}
foreach (GameObject powerBoostIncrease in playerPowerUpIncreaseScoreByTwoList)
{
if (powerBoostIncrease != null)
{
powerBoostIncrease.SetActive(true);
}
}
foreach (GameObject powerBoostIncreaseListParticle in playerPowerUpIncreaseScoreByTwoListParticle)
{
if (powerBoostIncreaseListParticle != null)
{
powerBoostIncreaseListParticle.SetActive(true);
}
}
}```
Quick question
It seems the default fill value of an imagine is 1f and trying to set it anything higher won't work, so is there a way to have it clamp to a higher value?
quickly looking at that code, this is terrible architecture
you should consider changing it
to something more extensible and more friendly to work with
why would you want a higher number?
fill image is clamped between 0 and 1
1 being the maximum fill amount
For ease of use.
1 shows the whole Image, what would be the point?
treat is kinda like visibility percentage
0 meaning 0% and 100 meaning 100%
there is no such thing as image visible at 200%
I meant having it shown 100% using a value of 0-100 or anything else instead of 0 to 1.
simple maths
E.g. percent / 100 if you want it 0-100
Okay got it.
Trying to make a Player movement, but I'm getting stuck on the mouse rotation.
This is my CameraMovement.cs script:
void Update()
{
mouseX = sensitivity * Input.GetAxisRaw("Mouse X");
orientation.transform.eulerAngles += new Vector3(0f, mouseX, 0f);
transform.eulerAngles = orientation.eulerAngles;
transform.position = orientation.position;
Debug.Log($"{orientation.eulerAngles.y} | {mouseX}");
}
and this is my PlayerMovement.cs script:
void Update()
{
MyInput();
}
void FixedUpdate()
{
Movement();
}
void MyInput()
{
vertical = Input.GetAxisRaw("Vertical");
horizontal = Input.GetAxisRaw("Horizontal");
moveDir = transform.forward * vertical + transform.right * horizontal;
}
void Movement()
{
rb.AddForce(moveDir.normalized * moveSpeed);
transform.eulerAngles = orientation.eulerAngles;
}
However, when I look around it continue rotate, even though I don't move the mouse. How do I fix this?
becaues you never reset it to zero
when you stop looking around
mouseX = sensitivity * Input.GetAxisRaw("Mouse X");
orientation.transform.eulerAngles += new Vector3(0f, mouseX, 0f);
you have += here
meaning if you dont move
it just won't add anything
but there is still a value from old rotation
if there's no input then mouseX should be 0 which means that would just be adding Vector3.zero to the rotation
yes but there is still old cached
orientation.transform.eulerAngles
it's never resetted
anytime there is input, it just adds
if you stop moving the mouse, it doesnt reset
it just doesnt add anything
why would they need to reset the current rotation back to 0
current rotation + 0 == current rotation
well if I don't add anything then it shouldn't rotate? :c
so is that what your debug returns though
Isn't this correct? Nothing happens when pressing space. I checked and using other variables from the script works.
if (Input.GetKey(KeyCode.Space) && script.DashReady == true)
{
ratio = 0f;
Debug.Log("RunBar");
}
have you ensured this code is being called? and have you ensured that the bool you are checking is actually true?
Yes I have, looking in the inspector it is true, and set to true at start as well
Could it be that in the other script it's being set to false when space is pressed?
yes, don't use the inspector to verify the values of your variables when things are not working the way you expect. the inspector will only display the last value from the frame. so if something set it to false for a very short amount of time, it's possible you did not see it. use the debugger or print the values
So shod I try adding a small delay to the value getting set to false?
what? i don't even know where this code is being executed at so how should i know if that would fix it?
The code: https://gdl.space/nazetihoda.cs
The Problem: The purpose of the script is that every time an object is added to the parentObject, it should save the name of the object in the list of prefabNames in the PlayerPrefs way, But the name is not added...
so you're still trying to fix the fundamentally flawed system that will not work at all in a build?
oh and what happens when an object's name gets (Clone) appended to it? you're not doing anything at all to handle that
but still, you should scrap this system and use one that won't bloat the registry on a user's computer and won't rely on game object names for logic
This is what I'm doing in the other script.
@slender nymph The truth bro, it works, I swear.
There was an error in the code this whole time
"it works" until you build the game because the folder you are relying on won't exist
Don't worry, I'll change the system sometime, I have more important things to do in the game!
okay so if this object's Update method happens before the other class's Update method then the other will never work
Hm.
So then how do I fix this?
i don't even know the purpose of these, but i'd assume you probably want some event instead ๐คทโโ๏ธ
i have 4 audio sources' i want them to play one after the other ( when one ends the other one begins) and when it gets to audio 4 it goes back to 1 and replays them again kinda like autoplay on 4 audios, how do i do that
do you really need 4 separate audio sources for that?
depending on your unity version an AudioRandomContainer could be useful there. otherwise you could just use a coroutine, play a sound then wait until it is no longer playing then play the next one and so on like that
tried a coroutine but i get this error
you are excluding some context that would explain why you are receiving that error
Your function has the wrong return type
that's now how you set up a coroutine, don't use the generic IEnumerable
It must be IEnumerator
but then i get another error
let me try
also i suggest you change the function name
still an error
show the code
And the error
did you even read the link?
also you still haven't said why you need multiple AudioSources for that instead of just a single audiosource and an array of clips
in this function the background is supposed to change
but for some reaosn it doesnt
it works for the wild pokmeon thoigh
because im an idiot and i cant code for shit
question
more audio sources instead of a clips array means bad performence?
cuz this scene takes a month to load
it's not about performance. it's just unnecessary unless you have a specific need for more than one audio source. but yes, it should reduce the time it takes for the scene to load because it will have fewer objects to load
(although 3 fewer objects won't impact it in a really noticeable way)
Is it better?
{
yield return new WaitForSecondsRealtime(delay);
RoundManager.Instance.currentState = GameState.OnSettings;
SetObjectsInactiveActive(false, false, false, false, true);
DeactivateGameObjects(treeLogsList);
DeactivateGameObjects(gemParticleList);
DeactivateGameObjects(powerUpList);
DeactivateGameObjects(playerPowerBoostListParticle);
DeactivateGameObjects(playerPowerUpIncreaseScoreByTwoList);
DeactivateGameObjects(playerPowerUpIncreaseScoreByTwoListParticle);
}
void DeactivateGameObjects(List<GameObject> objects)
{
foreach (GameObject obj in objects)
{
if (obj != null)
{
obj.SetActive(false);
}
}
}```
the scene itself has about 12 i can switch to arrays
the error is fixed, but it was a void before so i could attach the script to a dropdown, now its a coroutine so i cant attach it in the inspector
create a method that just starts the coroutine
so what is actually setting the background?
i need help because my timer script is not working at all and i don't know what to do or how to fix it.
Problem: It wont count down or up.
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class Timer : MonoBehaviour
{
[Header("Component")]
public TextMeshProUGUI timerText;
[Header("Timer Settings")]
public float currentTime;
public bool countDown;
[Header("Limit Settings")]
public bool hasLimit;
public float timerLimit;
[Header("Format Settings")]
public bool hasFormat;
public TimerFormats format;
private Dictionary<TimerFormats, string> timeFormats = new Dictionary<TimerFormats, string>();
// Start is called before the first frame update
void Start()
{
timeFormats.Add(TimerFormats.Whole, "0");
timeFormats.Add(TimerFormats.TenthDecimal, "0.0");
timeFormats.Add(TimerFormats.HundrethsDecimal, "0.00");
}
// Update is called once per frame
void Update()
{
currentTime = countDown ? currentTime -= Time.deltaTime : currentTime += Time.deltaTime;
if (hasLimit && ((countDown && currentTime <= timerLimit) || (!countDown && currentTime >= timerLimit)));
{
currentTime = timerLimit;
SetTimerText();
timerText.color = Color.red;
enabled = false;
}
SetTimerText();
}
private void SetTimerText()
{
timerText.text = hasFormat ? currentTime.ToString(timeFormats[format]) : currentTime.ToString();
}
}
public enum TimerFormats
{
Whole,
TenthDecimal,
HundrethsDecimal
}```
!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.
Your if statement in Update has something wrong, there's a semicolon ; at the end of the line so it will always run the block { ... } after it
thanks
in the set up battl efucntion
it works for the wild pokemon encounters
but not for the trainers
and what exactly doesn't work? it doesn't set it to the one you expect, or is it not setting it to any sprite at all?
ill show u
so there r 2 scenes
grassy and cave
when i encounter wild pokemon in grassy
ill get the grassy background
when i do it in cave
ill get cave bakgrond
like this
please just answer this question
however
when i do trainer battles
in grassy
i get grassy backgroudn
which is fine
but wehn i do a trainer battle in cave
thats wen it gies wrong
then either the you are not passing the correct enum, or the assigned sprite is wrong
i get grassy background
but it workd for wild pokemon
the background is set
via battle system
have you bothered inspecting the values instead of assuming everything is the way you expect?
values
yes the only two values that matter here, the enum passed to the StartTrainerBattle method and the sprite being assigned
pokemon game?
that is not what i meant. print the value of the variables in use so you can see what they are if you do not know how to use the debugger to actually inspect them
because there is nothing in it that would be affected by being disabled
Hey, I'm having trouble getting my head around how to create a new variable based upon how many elements are in my array, I'll create a thread to throw my code in ๐
the component itself I mean
i just told you why
sorry, I dont understand
there is nothing in your component that would be affected by being disabled, therefore unity does not render the checkbox to enable/disable it because that will do literally nothing at all
you mean parameters?
of course, in more recent versions that has changed so the tick box is there no matter what. but nothing will happen when you enable or disable that component so why should unity render that tick box?
!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.
But can I still disable the component by using code?
yes, but that will still do nothing at all
oh, so, what should I do?
for what? nothing is wrong here unless you are expecting anything to happen when the object is disabled
https://hastebin.com/share/qipasozula.java i cant find the thing that is inverting the movement cause it is such a long script and people are getting mad at me saying the idea of inverted movement is "shi"
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
this isn't related to the issue you are asking about, but do not multiply forces by deltaTime, nor should you multiply mouse input by deltaTime. dt is already factored into the AddForce call, you're just making your multipliers about 100 times higher than they need to be in order to compensate for that. and mouse input is already framerate independent so by multiplying by deltaTime you just end up with stuttery mouse controls
remove the deltaTime multiplications for your forces and for the mouse input
ok tysm
and of course reduce the values of the other multipliers to compensate
i just remembered something i have a old movement script i haven't used since 2020 and i feel like it might work.
nvm
I'm not great at explaining myself either but is anyone able to give some pointers?
im going to begin using unity learn since i dont know anything about unity. ima continue.
what should I include to the script in order to be able to disable it???
why do you need to disable it?
like genuinely, what purpose is that going to serve for code that is not going to be affected in any way by being disabled
Its has an OnCollision method
which is not affected by the component being disabled
I want to disable the component so that cant play
it isnt?
no. your code has no methods that would be affected by being disabled. that's what i've been telling you this whole time
ok, no need to remark that
you could ues dictionaries for that
backgroundImage.sprite = battleBackgrounds[battleTrigger]
Dictionary<BattleTrigger, Sprite>
extensible and designer-friendly
cuz if you want to add more backgrounds with current implementation it will get messy
with all the if/else checks
line 178 never runs, why??
lots of reasons:
- None of the code is ever running, including that line
- the
elseisn't being entered - There's an exception before that line
- The object running this coroutine was deactivated or destroyed before you got to that line. Coroutines don't run on deactivated or destroyed GameObjects
- it is running, i gets printed and it does what it needs to do before
- wdym isnt being entered?
- what does that mean
- i didnt destroy or deactivate any object, only thing was button.enabled = false, could that hav affected it?
because im an idiot ?
idk
- If the
ifruns, theelsewill not run - Any exception such as NullReferenceException or any other exception
if you have an exception you will likely see it as an error in the console
2 but that shouldnt matter right? since the loop itself runs. it only gets stuck at line 178
console is clean
only the print(i)
and print(hui") which was for testing
you sure errors are turned on in the console?
then the problem will be that your object was deactivated or destroyed
Hopefully this is better - https://paste.ofcode.org/sjU769RZnnanHmLtX8Z4Ku
but where
Oh one other possibility:
Time.timeScale is low or 0
in some other code that isn't pictured here?
hwo do i check that
print("Time scale is " + Time.timeScale);
on start?
I want to rotate the vector (0, Y, 0) by (0,0,Z) how do I do it?
clip is about 9 minutes, in the app i haev a skip forward button that sets the time to +5, could that be whats messing with it?
Vector3 rotatedVector = Quaternion.Euler(0,0,Z) * myVector;```
well your code is going to wait 9 minutes then.
its 0
what's 0
clip time
both of them are 0
prove it
that doesnt prove anything
only 2 things printed are i and time
that could be anything at the bottom there
and show the code aswell
Where and how are you running this loopDropdown function?
@wintry quarry
that doesn't answer my question
it does
running it in a script attached to the canvas, the funbctions itself is onvaluechanged when a dropdown option is selcted
no it does not
you logged the wrong thing
Can you show that code?
yeah this is not the log asked for
you logged time property
what do you mean its attached int he inspector
wanted to know the clip length
Right and you are referencing which object to do that?
is it a prefab?
right so it's 9 minutes as you said. Are you actually waiting 9 minutes before determining that it doesn't run?
that's a long time to wait
i use the skip button i mentioned earlier
Your coroutine doesn't know anything about that though.
your coroutine is waiting 9 minutes as you told it to do
so how do i let it know
a couple options
calculate the time it is supposed to wait
simplest is probably:
yield return new WaitWhile(() => songsource[i].isPlaying);```
so just replace yield return new WaitForSeconds(songsource[i].clip.length); with that?
another option is waiting in a loop and using your own timer which you can manipulate when pressing skip
try it and see lol
alrightt
"is playing cannot be used like a method"
how do I get the z rotation of an object, transform.rotation.z gives me number that are <1
already fixed it in my edit
thanks
what are you actually trying to do? This is the wrong way
explain in words
not in terms of angles and numbers
I have a 2D gun, and I want to shoot bullets in the directions it facing, I want to get the postion that x distance away from it with respect to its rotation
The direction it's facing is transform.up
the poisition x distance away would be transform.position + transform.up * distance;
you don't need to fuck with any angles
ok thanks
you can also do transform.TransformPoint(new Vector3(0, distance, 0)) although that will also respect scale
if (SpriteRenderer.flipX == true)
{
RB.velocity = new Vector2 ( -KBForce * NewCharacterMovement.speed , KBForce );
}
else
{
RB.velocity = new Vector2 ( KBForce * NewCharacterMovement.speed , KBForce );
}```
for some reason this script is not adding a velocity in the x direction
Have you done any debugging yet?
i dont know what to debug
how about:
- Is this code actually running?
- what are the values of these numbers?
-KBForce * NewCharacterMovement.speed
you know just the basic facts of the situation
why is there a layer in which all objects are invisible
kbforce works because it adds a velocity in the y direction, and newcharactermovement.speed is referencing a non 0 float from another script
you're making assumptions
Debug.Log is your next step
you need to question your assumptions at every step
Debug.Log(RB.velocity);
its apparently logging a horizontal velocity but its just not applied
sounds like the problem isn't with this code at all
it's with some other code
probably some other code is overwriting this
this is why we use Debug.Log
we have now ruled this code out as the problem and we are free to look elsewhere
yeah i think its because the velocity is set equal somewhere else in a fixed update function, but i dont understand how it would work for the y direction but not the x direction
probably because it's not changing the y in that other code
if the script is in the middle of running a for loop and then i tell it to run a diferent for loop will they both run at the same time or will the first for loop finish first
if the script is in the middle of running a for loop and then i tell it to run a diferent for loop
What does this even mean?
Show the code?
code runs top to bottom, in order
and only one line of code is running at a time
barring multithreading which you would be very aware of if you were doing it.
wait that doesnt matter anymore 3 more problems just came up that wil probably fix what i tried to fix when i fix them
sure but from academic curiosity I'm curious about waht you mean, and we may clear up some misconceptions you have about how code runs.
up to you
i get that its one line at a time i was just wondering if the code runs a for loop with a timer that takes 20 seconds, and while its waiting for the next command inside the for loop i press a button which runs a diffrent for loop. what happens
i assumed it waits but it doesnt
but it also doesnt does
nevermind
im overcomplicating
I guess you're asking something about coroutines
because under normal circumstances "pressing a button" is not something that can be done or detected in the middle of a loop
i have this class ```cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace GK
{
public class LSystemBranch : MonoBehaviour
{
public Transform plantPrefab;
public float minSegmentLength = 0.5f;
public float maxSegmentLength = 2f;
public float Length;
public List<Vector3> previousEndPoints = new List<Vector3>();
public List<Vector3> firstStartPoints = new List<Vector3>();
private int plantSegmentNumber;
public int totalNumberOfPlantSegments = 15;
public int numSides;
public Vector3 offsetrotation = new Vector3();
void Start()
{
createBranch();
}```
how do i create a LSystem branch object in another class and set some of the public variables before it runs?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace GK
{
//add a branch
public class Branch1 = LSystemBranch();
} ```
so how does it work
forget about the issue
if u tell a script to do one thing and at the same time another while its busy
you'd really have to show a code example because your question is a bit vague
okay one sec
this isn't possible in general so I'd like to see an example of what you mean
basically while the loop is running nothing else can happen, UNLESS we're talking about coroutines
something like this
while btn() is running u call btn2()
if a script only renders one line at a time
does it just jump andcome back
cuz it cant leave a for loop
oh the waitforseconds is supposed to be in a for loop***********
The way WaitForSeconds works is every frame Unity checks to see if the time has passed. If it has, it continues running that code. If not, it comes back again next frame
eithe way the code is not running at the same time
it will be something like:
Frame Start
Unity checks the coroutines. If time elapsed, the coroutine runs fully until the next yield
Update runs on your scripts and the event system and potentially you run btn2()
Frame End
Next Frame```
there's no magic
i dont undestand anthing u just wrote
What part are you confused about
how do i create a LSystem branch object
var branch = Instantiate(LSystemBranch);```
> set some public variables before 'Start' runs
```cs
var branch = Instantiate(LSystemBranch);
branch.Init(...);
branch.enabled = true;```*You could have the component or game object disable/inactive if necessary*
Unity like most game engines runs on a frame by frame basis
not really. It prints whenever that input is processed
most likely in your script's Update function
and its only proccessed when th for loop is over?
no
if there's a yield in the middle of the loop, the loop can be paused
yield pauses the code and lets the rest of the engine run
ohh
that's all that yield does
so waitforsecondslets the line reader to read all the other lines in the code
without making it stuck
if there's no yield, then the entire game engine is frozen until your code is done running
this is true for all code you write anywhere in Unity
(excepting multithreading but that's another subject)
but it proccesse the code so fast u dont notice right
I could be wrong, so apologies if I am, but, ignore the code you have written for a minute.
Logically, Unity will read your script from top to bottom - but, since you have set up Coroutines, it will run them AS WELL as the "Update" section of your code, so "Update" will always run, but you can control Coroutines with delays so they might not always run on every frame.
yes
unless you screw up and write an infinite loop or other code that takes a very long time
then your game freezes or your framerate suffers
Yo guys, I have code that moves and instantiated object however when the object spawns on start, the code doesnt run. Anyone know what went wrong?
ok i think i get it
You'd have to show code etc
What script is this? What code isn't running?
is the tool bar suppose to be in the top left of the editor? Is there a way to reposition into the top left corner of scene view?
IDK how you got it there tbh lol
Hi I just joined
I want to learn how to code in C#
Does anyone know any places I can learn?
This is a great place to start https://dotnet.microsoft.com/en-us/learn/csharp
I have an autoplay system on my unity project that is selected by using a dropdown. if i set it to autoplay before i pressed the start playing music button, it enables all of the songs at once and when i press play it starts them all, however when i first press the play button and then press auto play it works just fine, i assume its becuase the auto play works by waiting for the song before to end before starting another one but none are playing since i havent started yet. i hope you get what i mean, i just havent been able to pinpoint the problem and find a solution https://codeshare.io/xLeb8R
Ah okay thank you
I can still use the key binds so its not a huge deal, just trying to mimic the tutorial lmao
Codecademy also is pretty good for learning the basics of programming. I wouldn't recommend the paid version personally
Try Window -> Layouts -> Default
I will try that
Tried all layouts doesnt effect the tool bar
I can't even get the scene overlays out of the scene window IDK how you managed it lol
How do I make the variables for 'ranged weapon' disappear if 'is ranged' is disabled?
A custom editor/property drawer
Or use an off the shelf one like NaughtyAttributes
I think I know what it is
what version is current for unity?
I already have NaughtyAttributes
so I'm looking through an open-source GuitarHero clone project and I see they have a bunch of classes defined in their "Player" script, and I'm curious why?
Then use ShowIf/HideIf
so like, [ShowIf("isRanged", true)]?
just [ShowIf("isRanged")]
why not? They're probably used within the Player script
I guess like what's the benefit over defining this vars in a class rather than just having them live in the main class?
they become portable/reusable? You can make an array of them?
YOu can serialize them separately
you can copy them around
etc
Yo guys, I want an object in my game to recognise the player and always knows it transform.position but I cant make a game object variable as the object will be instantiated so using prefabs wont work, is there anyway to do this?
assign the reference after you instantiate
ooh I can see that, okay thank you, that does make sense I'll look through the rest of it baring that functionality in mind
@wintry quarry I think I was on an older verison of unity thanks for the help
For example:
public class EnemySpawner : MonoBehaviour {
public Enemy enemyPrefab; // assign in inspector to the prefab
public Transform player; // assign in inspector to the player in the scnee
void SpawnEnemy() {
Enemy newEnemy = Instantiate(enemyPrefab);
newEnemy.target = player;
}
}```
I can do that???
Yes, the Instantiate<T>(T original) method returns the T spawned, so you're able to store its reference
Well I can do it. And if I can do it, you can do it too!
for some reason that isn't doing anything
show what you tried
did you save the code
yes
Do you have a custom editor for this script
btw this is inside a class that doesn't inherit from monobehaviour, but I think this doesn't change anything because I was able to use attributes from naughtyattributes and unity before in class
nope
Hmm I think that only works for Drawer Attributes